1 /* Remote target communications for serial-line targets in custom GDB protocol
3 Copyright (C) 1988-2012 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 /* See the GDB User Guide for details of the GDB remote protocol. */
23 #include "gdb_string.h"
29 #include "exceptions.h"
31 /*#include "terminal.h" */
34 #include "gdb-stabs.h"
35 #include "gdbthread.h"
39 #include "gdb_assert.h"
42 #include "cli/cli-decode.h"
43 #include "cli/cli-setshow.h"
44 #include "target-descriptions.h"
49 #include "event-loop.h"
50 #include "event-top.h"
56 #include "gdbcore.h" /* for exec_bfd */
58 #include "remote-fileio.h"
59 #include "gdb/fileio.h"
61 #include "xml-support.h"
63 #include "memory-map.h"
65 #include "tracepoint.h"
70 /* Temp hacks for tracepoint encoding migration. */
71 static char *target_buf;
72 static long target_buf_size;
74 /* The size to align memory write packets, when practical. The protocol
75 does not guarantee any alignment, and gdb will generate short
76 writes and unaligned writes, but even as a best-effort attempt this
77 can improve bulk transfers. For instance, if a write is misaligned
78 relative to the target's data bus, the stub may need to make an extra
79 round trip fetching data from the target. This doesn't make a
80 huge difference, but it's easy to do, so we try to be helpful.
82 The alignment chosen is arbitrary; usually data bus width is
83 important here, not the possibly larger cache line size. */
84 enum { REMOTE_ALIGN_WRITES = 16 };
86 /* Prototypes for local functions. */
87 static void cleanup_sigint_signal_handler (void *dummy);
88 static void initialize_sigint_signal_handler (void);
89 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
90 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
93 static void handle_remote_sigint (int);
94 static void handle_remote_sigint_twice (int);
95 static void async_remote_interrupt (gdb_client_data);
96 void async_remote_interrupt_twice (gdb_client_data);
98 static void remote_files_info (struct target_ops *ignore);
100 static void remote_prepare_to_store (struct regcache *regcache);
102 static void remote_open (char *name, int from_tty);
104 static void extended_remote_open (char *name, int from_tty);
106 static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
108 static void remote_close (int quitting);
110 static void remote_mourn (struct target_ops *ops);
112 static void extended_remote_restart (void);
114 static void extended_remote_mourn (struct target_ops *);
116 static void remote_mourn_1 (struct target_ops *);
118 static void remote_send (char **buf, long *sizeof_buf_p);
120 static int readchar (int timeout);
122 static void remote_kill (struct target_ops *ops);
124 static int tohex (int nib);
126 static int remote_can_async_p (void);
128 static int remote_is_async_p (void);
130 static void remote_async (void (*callback) (enum inferior_event_type event_type,
131 void *context), void *context);
133 static void remote_detach (struct target_ops *ops, char *args, int from_tty);
135 static void remote_interrupt (int signo);
137 static void remote_interrupt_twice (int signo);
139 static void interrupt_query (void);
141 static void set_general_thread (struct ptid ptid);
142 static void set_continue_thread (struct ptid ptid);
144 static void get_offsets (void);
146 static void skip_frame (void);
148 static long read_frame (char **buf_p, long *sizeof_buf);
150 static int hexnumlen (ULONGEST num);
152 static void init_remote_ops (void);
154 static void init_extended_remote_ops (void);
156 static void remote_stop (ptid_t);
158 static int ishex (int ch, int *val);
160 static int stubhex (int ch);
162 static int hexnumstr (char *, ULONGEST);
164 static int hexnumnstr (char *, ULONGEST, int);
166 static CORE_ADDR remote_address_masked (CORE_ADDR);
168 static void print_packet (char *);
170 static void compare_sections_command (char *, int);
172 static void packet_command (char *, int);
174 static int stub_unpack_int (char *buff, int fieldlength);
176 static ptid_t remote_current_thread (ptid_t oldptid);
178 static void remote_find_new_threads (void);
180 static void record_currthread (ptid_t currthread);
182 static int fromhex (int a);
184 extern int hex2bin (const char *hex, gdb_byte *bin, int count);
186 extern int bin2hex (const gdb_byte *bin, char *hex, int count);
188 static int putpkt_binary (char *buf, int cnt);
190 static void check_binary_download (CORE_ADDR addr);
192 struct packet_config;
194 static void show_packet_config_cmd (struct packet_config *config);
196 static void update_packet_config (struct packet_config *config);
198 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
199 struct cmd_list_element *c);
201 static void show_remote_protocol_packet_cmd (struct ui_file *file,
203 struct cmd_list_element *c,
206 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
207 static ptid_t read_ptid (char *buf, char **obuf);
209 static void remote_set_permissions (void);
212 static int remote_get_trace_status (struct trace_status *ts);
214 static int remote_upload_tracepoints (struct uploaded_tp **utpp);
216 static int remote_upload_trace_state_variables (struct uploaded_tsv **utsvp);
218 static void remote_query_supported (void);
220 static void remote_check_symbols (struct objfile *objfile);
222 void _initialize_remote (void);
225 static struct stop_reply *stop_reply_xmalloc (void);
226 static void stop_reply_xfree (struct stop_reply *);
227 static void do_stop_reply_xfree (void *arg);
228 static void remote_parse_stop_reply (char *buf, struct stop_reply *);
229 static void push_stop_reply (struct stop_reply *);
230 static void remote_get_pending_stop_replies (void);
231 static void discard_pending_stop_replies (int pid);
232 static int peek_stop_reply (ptid_t ptid);
234 static void remote_async_inferior_event_handler (gdb_client_data);
235 static void remote_async_get_pending_events_handler (gdb_client_data);
237 static void remote_terminal_ours (void);
239 static int remote_read_description_p (struct target_ops *target);
241 static void remote_console_output (char *msg);
243 static int remote_supports_cond_breakpoints (void);
245 /* The non-stop remote protocol provisions for one pending stop reply.
246 This is where we keep it until it is acknowledged. */
248 static struct stop_reply *pending_stop_reply = NULL;
252 static struct cmd_list_element *remote_cmdlist;
254 /* For "set remote" and "show remote". */
256 static struct cmd_list_element *remote_set_cmdlist;
257 static struct cmd_list_element *remote_show_cmdlist;
259 /* Description of the remote protocol state for the currently
260 connected target. This is per-target state, and independent of the
261 selected architecture. */
265 /* A buffer to use for incoming packets, and its current size. The
266 buffer is grown dynamically for larger incoming packets.
267 Outgoing packets may also be constructed in this buffer.
268 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
269 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
274 /* If we negotiated packet size explicitly (and thus can bypass
275 heuristics for the largest packet size that will not overflow
276 a buffer in the stub), this will be set to that packet size.
277 Otherwise zero, meaning to use the guessed size. */
278 long explicit_packet_size;
280 /* remote_wait is normally called when the target is running and
281 waits for a stop reply packet. But sometimes we need to call it
282 when the target is already stopped. We can send a "?" packet
283 and have remote_wait read the response. Or, if we already have
284 the response, we can stash it in BUF and tell remote_wait to
285 skip calling getpkt. This flag is set when BUF contains a
286 stop reply packet and the target is not waiting. */
287 int cached_wait_status;
289 /* True, if in no ack mode. That is, neither GDB nor the stub will
290 expect acks from each other. The connection is assumed to be
294 /* True if we're connected in extended remote mode. */
297 /* True if the stub reported support for multi-process
299 int multi_process_aware;
301 /* True if we resumed the target and we're waiting for the target to
302 stop. In the mean time, we can't start another command/query.
303 The remote server wouldn't be ready to process it, so we'd
304 timeout waiting for a reply that would never come and eventually
305 we'd close the connection. This can happen in asynchronous mode
306 because we allow GDB commands while the target is running. */
307 int waiting_for_stop_reply;
309 /* True if the stub reports support for non-stop mode. */
312 /* True if the stub reports support for vCont;t. */
315 /* True if the stub reports support for conditional tracepoints. */
316 int cond_tracepoints;
318 /* True if the stub reports support for target-side breakpoint
320 int cond_breakpoints;
322 /* True if the stub reports support for fast tracepoints. */
323 int fast_tracepoints;
325 /* True if the stub reports support for static tracepoints. */
326 int static_tracepoints;
328 /* True if the stub reports support for installing tracepoint while
330 int install_in_trace;
332 /* True if the stub can continue running a trace while GDB is
334 int disconnected_tracing;
336 /* True if the stub reports support for enabling and disabling
337 tracepoints while a trace experiment is running. */
338 int enable_disable_tracepoints;
340 /* True if the stub can collect strings using tracenz bytecode. */
343 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
344 responded to that. */
348 /* Private data that we'll store in (struct thread_info)->private. */
349 struct private_thread_info
356 free_private_thread_info (struct private_thread_info *info)
362 /* Returns true if the multi-process extensions are in effect. */
364 remote_multi_process_p (struct remote_state *rs)
366 return rs->multi_process_aware;
369 /* This data could be associated with a target, but we do not always
370 have access to the current target when we need it, so for now it is
371 static. This will be fine for as long as only one target is in use
373 static struct remote_state remote_state;
375 static struct remote_state *
376 get_remote_state_raw (void)
378 return &remote_state;
381 /* Description of the remote protocol for a given architecture. */
385 long offset; /* Offset into G packet. */
386 long regnum; /* GDB's internal register number. */
387 LONGEST pnum; /* Remote protocol register number. */
388 int in_g_packet; /* Always part of G packet. */
389 /* long size in bytes; == register_size (target_gdbarch, regnum);
391 /* char *name; == gdbarch_register_name (target_gdbarch, regnum);
395 struct remote_arch_state
397 /* Description of the remote protocol registers. */
398 long sizeof_g_packet;
400 /* Description of the remote protocol registers indexed by REGNUM
401 (making an array gdbarch_num_regs in size). */
402 struct packet_reg *regs;
404 /* This is the size (in chars) of the first response to the ``g''
405 packet. It is used as a heuristic when determining the maximum
406 size of memory-read and memory-write packets. A target will
407 typically only reserve a buffer large enough to hold the ``g''
408 packet. The size does not include packet overhead (headers and
410 long actual_register_packet_size;
412 /* This is the maximum size (in chars) of a non read/write packet.
413 It is also used as a cap on the size of read/write packets. */
414 long remote_packet_size;
417 long sizeof_pkt = 2000;
419 /* Utility: generate error from an incoming stub packet. */
421 trace_error (char *buf)
424 return; /* not an error msg */
427 case '1': /* malformed packet error */
428 if (*++buf == '0') /* general case: */
429 error (_("remote.c: error in outgoing packet."));
431 error (_("remote.c: error in outgoing packet at field #%ld."),
432 strtol (buf, NULL, 16));
434 error (_("trace API error 0x%s."), ++buf);
436 error (_("Target returns error code '%s'."), buf);
440 /* Utility: wait for reply from stub, while accepting "O" packets. */
442 remote_get_noisy_reply (char **buf_p,
445 do /* Loop on reply from remote stub. */
449 QUIT; /* Allow user to bail out with ^C. */
450 getpkt (buf_p, sizeof_buf, 0);
454 else if (strncmp (buf, "qRelocInsn:", strlen ("qRelocInsn:")) == 0)
457 CORE_ADDR from, to, org_to;
459 int adjusted_size = 0;
460 volatile struct gdb_exception ex;
462 p = buf + strlen ("qRelocInsn:");
463 pp = unpack_varlen_hex (p, &ul);
465 error (_("invalid qRelocInsn packet: %s"), buf);
469 unpack_varlen_hex (p, &ul);
474 TRY_CATCH (ex, RETURN_MASK_ALL)
476 gdbarch_relocate_instruction (target_gdbarch, &to, from);
480 adjusted_size = to - org_to;
482 sprintf (buf, "qRelocInsn:%x", adjusted_size);
485 else if (ex.reason < 0 && ex.error == MEMORY_ERROR)
487 /* Propagate memory errors silently back to the target.
488 The stub may have limited the range of addresses we
489 can write to, for example. */
494 /* Something unexpectedly bad happened. Be verbose so
495 we can tell what, and propagate the error back to the
496 stub, so it doesn't get stuck waiting for a
498 exception_fprintf (gdb_stderr, ex,
499 _("warning: relocating instruction: "));
503 else if (buf[0] == 'O' && buf[1] != 'K')
504 remote_console_output (buf + 1); /* 'O' message from stub */
506 return buf; /* Here's the actual reply. */
511 /* Handle for retreving the remote protocol data from gdbarch. */
512 static struct gdbarch_data *remote_gdbarch_data_handle;
514 static struct remote_arch_state *
515 get_remote_arch_state (void)
517 return gdbarch_data (target_gdbarch, remote_gdbarch_data_handle);
520 /* Fetch the global remote target state. */
522 static struct remote_state *
523 get_remote_state (void)
525 /* Make sure that the remote architecture state has been
526 initialized, because doing so might reallocate rs->buf. Any
527 function which calls getpkt also needs to be mindful of changes
528 to rs->buf, but this call limits the number of places which run
530 get_remote_arch_state ();
532 return get_remote_state_raw ();
536 compare_pnums (const void *lhs_, const void *rhs_)
538 const struct packet_reg * const *lhs = lhs_;
539 const struct packet_reg * const *rhs = rhs_;
541 if ((*lhs)->pnum < (*rhs)->pnum)
543 else if ((*lhs)->pnum == (*rhs)->pnum)
550 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
552 int regnum, num_remote_regs, offset;
553 struct packet_reg **remote_regs;
555 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
557 struct packet_reg *r = ®s[regnum];
559 if (register_size (gdbarch, regnum) == 0)
560 /* Do not try to fetch zero-sized (placeholder) registers. */
563 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
568 /* Define the g/G packet format as the contents of each register
569 with a remote protocol number, in order of ascending protocol
572 remote_regs = alloca (gdbarch_num_regs (gdbarch)
573 * sizeof (struct packet_reg *));
574 for (num_remote_regs = 0, regnum = 0;
575 regnum < gdbarch_num_regs (gdbarch);
577 if (regs[regnum].pnum != -1)
578 remote_regs[num_remote_regs++] = ®s[regnum];
580 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
583 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
585 remote_regs[regnum]->in_g_packet = 1;
586 remote_regs[regnum]->offset = offset;
587 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
593 /* Given the architecture described by GDBARCH, return the remote
594 protocol register's number and the register's offset in the g/G
595 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
596 If the target does not have a mapping for REGNUM, return false,
597 otherwise, return true. */
600 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
601 int *pnum, int *poffset)
604 struct packet_reg *regs;
605 struct cleanup *old_chain;
607 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
609 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
610 old_chain = make_cleanup (xfree, regs);
612 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
614 *pnum = regs[regnum].pnum;
615 *poffset = regs[regnum].offset;
617 do_cleanups (old_chain);
623 init_remote_state (struct gdbarch *gdbarch)
625 struct remote_state *rs = get_remote_state_raw ();
626 struct remote_arch_state *rsa;
628 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
630 /* Use the architecture to build a regnum<->pnum table, which will be
631 1:1 unless a feature set specifies otherwise. */
632 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
633 gdbarch_num_regs (gdbarch),
636 /* Record the maximum possible size of the g packet - it may turn out
638 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
640 /* Default maximum number of characters in a packet body. Many
641 remote stubs have a hardwired buffer size of 400 bytes
642 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
643 as the maximum packet-size to ensure that the packet and an extra
644 NUL character can always fit in the buffer. This stops GDB
645 trashing stubs that try to squeeze an extra NUL into what is
646 already a full buffer (As of 1999-12-04 that was most stubs). */
647 rsa->remote_packet_size = 400 - 1;
649 /* This one is filled in when a ``g'' packet is received. */
650 rsa->actual_register_packet_size = 0;
652 /* Should rsa->sizeof_g_packet needs more space than the
653 default, adjust the size accordingly. Remember that each byte is
654 encoded as two characters. 32 is the overhead for the packet
655 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
656 (``$NN:G...#NN'') is a better guess, the below has been padded a
658 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
659 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
661 /* Make sure that the packet buffer is plenty big enough for
662 this architecture. */
663 if (rs->buf_size < rsa->remote_packet_size)
665 rs->buf_size = 2 * rsa->remote_packet_size;
666 rs->buf = xrealloc (rs->buf, rs->buf_size);
672 /* Return the current allowed size of a remote packet. This is
673 inferred from the current architecture, and should be used to
674 limit the length of outgoing packets. */
676 get_remote_packet_size (void)
678 struct remote_state *rs = get_remote_state ();
679 struct remote_arch_state *rsa = get_remote_arch_state ();
681 if (rs->explicit_packet_size)
682 return rs->explicit_packet_size;
684 return rsa->remote_packet_size;
687 static struct packet_reg *
688 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
690 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch))
694 struct packet_reg *r = &rsa->regs[regnum];
696 gdb_assert (r->regnum == regnum);
701 static struct packet_reg *
702 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
706 for (i = 0; i < gdbarch_num_regs (target_gdbarch); i++)
708 struct packet_reg *r = &rsa->regs[i];
716 /* FIXME: graces/2002-08-08: These variables should eventually be
717 bound to an instance of the target object (as in gdbarch-tdep()),
718 when such a thing exists. */
720 /* This is set to the data address of the access causing the target
721 to stop for a watchpoint. */
722 static CORE_ADDR remote_watch_data_address;
724 /* This is non-zero if target stopped for a watchpoint. */
725 static int remote_stopped_by_watchpoint_p;
727 static struct target_ops remote_ops;
729 static struct target_ops extended_remote_ops;
731 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
732 ``forever'' still use the normal timeout mechanism. This is
733 currently used by the ASYNC code to guarentee that target reads
734 during the initial connect always time-out. Once getpkt has been
735 modified to return a timeout indication and, in turn
736 remote_wait()/wait_for_inferior() have gained a timeout parameter
738 static int wait_forever_enabled_p = 1;
740 /* Allow the user to specify what sequence to send to the remote
741 when he requests a program interruption: Although ^C is usually
742 what remote systems expect (this is the default, here), it is
743 sometimes preferable to send a break. On other systems such
744 as the Linux kernel, a break followed by g, which is Magic SysRq g
745 is required in order to interrupt the execution. */
746 const char interrupt_sequence_control_c[] = "Ctrl-C";
747 const char interrupt_sequence_break[] = "BREAK";
748 const char interrupt_sequence_break_g[] = "BREAK-g";
749 static const char *const interrupt_sequence_modes[] =
751 interrupt_sequence_control_c,
752 interrupt_sequence_break,
753 interrupt_sequence_break_g,
756 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
759 show_interrupt_sequence (struct ui_file *file, int from_tty,
760 struct cmd_list_element *c,
763 if (interrupt_sequence_mode == interrupt_sequence_control_c)
764 fprintf_filtered (file,
765 _("Send the ASCII ETX character (Ctrl-c) "
766 "to the remote target to interrupt the "
767 "execution of the program.\n"));
768 else if (interrupt_sequence_mode == interrupt_sequence_break)
769 fprintf_filtered (file,
770 _("send a break signal to the remote target "
771 "to interrupt the execution of the program.\n"));
772 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
773 fprintf_filtered (file,
774 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
775 "the remote target to interrupt the execution "
776 "of Linux kernel.\n"));
778 internal_error (__FILE__, __LINE__,
779 _("Invalid value for interrupt_sequence_mode: %s."),
780 interrupt_sequence_mode);
783 /* This boolean variable specifies whether interrupt_sequence is sent
784 to the remote target when gdb connects to it.
785 This is mostly needed when you debug the Linux kernel: The Linux kernel
786 expects BREAK g which is Magic SysRq g for connecting gdb. */
787 static int interrupt_on_connect = 0;
789 /* This variable is used to implement the "set/show remotebreak" commands.
790 Since these commands are now deprecated in favor of "set/show remote
791 interrupt-sequence", it no longer has any effect on the code. */
792 static int remote_break;
795 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
798 interrupt_sequence_mode = interrupt_sequence_break;
800 interrupt_sequence_mode = interrupt_sequence_control_c;
804 show_remotebreak (struct ui_file *file, int from_tty,
805 struct cmd_list_element *c,
810 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
811 remote_open knows that we don't have a file open when the program
813 static struct serial *remote_desc = NULL;
815 /* This variable sets the number of bits in an address that are to be
816 sent in a memory ("M" or "m") packet. Normally, after stripping
817 leading zeros, the entire address would be sent. This variable
818 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
819 initial implementation of remote.c restricted the address sent in
820 memory packets to ``host::sizeof long'' bytes - (typically 32
821 bits). Consequently, for 64 bit targets, the upper 32 bits of an
822 address was never sent. Since fixing this bug may cause a break in
823 some remote targets this variable is principly provided to
824 facilitate backward compatibility. */
826 static int remote_address_size;
828 /* Temporary to track who currently owns the terminal. See
829 remote_terminal_* for more details. */
831 static int remote_async_terminal_ours_p;
833 /* The executable file to use for "run" on the remote side. */
835 static char *remote_exec_file = "";
838 /* User configurable variables for the number of characters in a
839 memory read/write packet. MIN (rsa->remote_packet_size,
840 rsa->sizeof_g_packet) is the default. Some targets need smaller
841 values (fifo overruns, et.al.) and some users need larger values
842 (speed up transfers). The variables ``preferred_*'' (the user
843 request), ``current_*'' (what was actually set) and ``forced_*''
844 (Positive - a soft limit, negative - a hard limit). */
846 struct memory_packet_config
853 /* Compute the current size of a read/write packet. Since this makes
854 use of ``actual_register_packet_size'' the computation is dynamic. */
857 get_memory_packet_size (struct memory_packet_config *config)
859 struct remote_state *rs = get_remote_state ();
860 struct remote_arch_state *rsa = get_remote_arch_state ();
862 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
863 law?) that some hosts don't cope very well with large alloca()
864 calls. Eventually the alloca() code will be replaced by calls to
865 xmalloc() and make_cleanups() allowing this restriction to either
866 be lifted or removed. */
867 #ifndef MAX_REMOTE_PACKET_SIZE
868 #define MAX_REMOTE_PACKET_SIZE 16384
870 /* NOTE: 20 ensures we can write at least one byte. */
871 #ifndef MIN_REMOTE_PACKET_SIZE
872 #define MIN_REMOTE_PACKET_SIZE 20
877 if (config->size <= 0)
878 what_they_get = MAX_REMOTE_PACKET_SIZE;
880 what_they_get = config->size;
884 what_they_get = get_remote_packet_size ();
885 /* Limit the packet to the size specified by the user. */
887 && what_they_get > config->size)
888 what_they_get = config->size;
890 /* Limit it to the size of the targets ``g'' response unless we have
891 permission from the stub to use a larger packet size. */
892 if (rs->explicit_packet_size == 0
893 && rsa->actual_register_packet_size > 0
894 && what_they_get > rsa->actual_register_packet_size)
895 what_they_get = rsa->actual_register_packet_size;
897 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
898 what_they_get = MAX_REMOTE_PACKET_SIZE;
899 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
900 what_they_get = MIN_REMOTE_PACKET_SIZE;
902 /* Make sure there is room in the global buffer for this packet
903 (including its trailing NUL byte). */
904 if (rs->buf_size < what_they_get + 1)
906 rs->buf_size = 2 * what_they_get;
907 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
910 return what_they_get;
913 /* Update the size of a read/write packet. If they user wants
914 something really big then do a sanity check. */
917 set_memory_packet_size (char *args, struct memory_packet_config *config)
919 int fixed_p = config->fixed_p;
920 long size = config->size;
923 error (_("Argument required (integer, `fixed' or `limited')."));
924 else if (strcmp (args, "hard") == 0
925 || strcmp (args, "fixed") == 0)
927 else if (strcmp (args, "soft") == 0
928 || strcmp (args, "limit") == 0)
934 size = strtoul (args, &end, 0);
936 error (_("Invalid %s (bad syntax)."), config->name);
938 /* Instead of explicitly capping the size of a packet to
939 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
940 instead allowed to set the size to something arbitrarily
942 if (size > MAX_REMOTE_PACKET_SIZE)
943 error (_("Invalid %s (too large)."), config->name);
947 if (fixed_p && !config->fixed_p)
949 if (! query (_("The target may not be able to correctly handle a %s\n"
950 "of %ld bytes. Change the packet size? "),
952 error (_("Packet size not changed."));
954 /* Update the config. */
955 config->fixed_p = fixed_p;
960 show_memory_packet_size (struct memory_packet_config *config)
962 printf_filtered (_("The %s is %ld. "), config->name, config->size);
964 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
965 get_memory_packet_size (config));
967 printf_filtered (_("Packets are limited to %ld bytes.\n"),
968 get_memory_packet_size (config));
971 static struct memory_packet_config memory_write_packet_config =
973 "memory-write-packet-size",
977 set_memory_write_packet_size (char *args, int from_tty)
979 set_memory_packet_size (args, &memory_write_packet_config);
983 show_memory_write_packet_size (char *args, int from_tty)
985 show_memory_packet_size (&memory_write_packet_config);
989 get_memory_write_packet_size (void)
991 return get_memory_packet_size (&memory_write_packet_config);
994 static struct memory_packet_config memory_read_packet_config =
996 "memory-read-packet-size",
1000 set_memory_read_packet_size (char *args, int from_tty)
1002 set_memory_packet_size (args, &memory_read_packet_config);
1006 show_memory_read_packet_size (char *args, int from_tty)
1008 show_memory_packet_size (&memory_read_packet_config);
1012 get_memory_read_packet_size (void)
1014 long size = get_memory_packet_size (&memory_read_packet_config);
1016 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1017 extra buffer size argument before the memory read size can be
1018 increased beyond this. */
1019 if (size > get_remote_packet_size ())
1020 size = get_remote_packet_size ();
1025 /* Generic configuration support for packets the stub optionally
1026 supports. Allows the user to specify the use of the packet as well
1027 as allowing GDB to auto-detect support in the remote stub. */
1031 PACKET_SUPPORT_UNKNOWN = 0,
1036 struct packet_config
1040 enum auto_boolean detect;
1041 enum packet_support support;
1044 /* Analyze a packet's return value and update the packet config
1055 update_packet_config (struct packet_config *config)
1057 switch (config->detect)
1059 case AUTO_BOOLEAN_TRUE:
1060 config->support = PACKET_ENABLE;
1062 case AUTO_BOOLEAN_FALSE:
1063 config->support = PACKET_DISABLE;
1065 case AUTO_BOOLEAN_AUTO:
1066 config->support = PACKET_SUPPORT_UNKNOWN;
1072 show_packet_config_cmd (struct packet_config *config)
1074 char *support = "internal-error";
1076 switch (config->support)
1079 support = "enabled";
1081 case PACKET_DISABLE:
1082 support = "disabled";
1084 case PACKET_SUPPORT_UNKNOWN:
1085 support = "unknown";
1088 switch (config->detect)
1090 case AUTO_BOOLEAN_AUTO:
1091 printf_filtered (_("Support for the `%s' packet "
1092 "is auto-detected, currently %s.\n"),
1093 config->name, support);
1095 case AUTO_BOOLEAN_TRUE:
1096 case AUTO_BOOLEAN_FALSE:
1097 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1098 config->name, support);
1104 add_packet_config_cmd (struct packet_config *config, const char *name,
1105 const char *title, int legacy)
1111 config->name = name;
1112 config->title = title;
1113 config->detect = AUTO_BOOLEAN_AUTO;
1114 config->support = PACKET_SUPPORT_UNKNOWN;
1115 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1117 show_doc = xstrprintf ("Show current use of remote "
1118 "protocol `%s' (%s) packet",
1120 /* set/show TITLE-packet {auto,on,off} */
1121 cmd_name = xstrprintf ("%s-packet", title);
1122 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1123 &config->detect, set_doc,
1124 show_doc, NULL, /* help_doc */
1125 set_remote_protocol_packet_cmd,
1126 show_remote_protocol_packet_cmd,
1127 &remote_set_cmdlist, &remote_show_cmdlist);
1128 /* The command code copies the documentation strings. */
1131 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
1136 legacy_name = xstrprintf ("%s-packet", name);
1137 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1138 &remote_set_cmdlist);
1139 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1140 &remote_show_cmdlist);
1144 static enum packet_result
1145 packet_check_result (const char *buf)
1149 /* The stub recognized the packet request. Check that the
1150 operation succeeded. */
1152 && isxdigit (buf[1]) && isxdigit (buf[2])
1154 /* "Enn" - definitly an error. */
1155 return PACKET_ERROR;
1157 /* Always treat "E." as an error. This will be used for
1158 more verbose error messages, such as E.memtypes. */
1159 if (buf[0] == 'E' && buf[1] == '.')
1160 return PACKET_ERROR;
1162 /* The packet may or may not be OK. Just assume it is. */
1166 /* The stub does not support the packet. */
1167 return PACKET_UNKNOWN;
1170 static enum packet_result
1171 packet_ok (const char *buf, struct packet_config *config)
1173 enum packet_result result;
1175 result = packet_check_result (buf);
1180 /* The stub recognized the packet request. */
1181 switch (config->support)
1183 case PACKET_SUPPORT_UNKNOWN:
1185 fprintf_unfiltered (gdb_stdlog,
1186 "Packet %s (%s) is supported\n",
1187 config->name, config->title);
1188 config->support = PACKET_ENABLE;
1190 case PACKET_DISABLE:
1191 internal_error (__FILE__, __LINE__,
1192 _("packet_ok: attempt to use a disabled packet"));
1198 case PACKET_UNKNOWN:
1199 /* The stub does not support the packet. */
1200 switch (config->support)
1203 if (config->detect == AUTO_BOOLEAN_AUTO)
1204 /* If the stub previously indicated that the packet was
1205 supported then there is a protocol error.. */
1206 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1207 config->name, config->title);
1209 /* The user set it wrong. */
1210 error (_("Enabled packet %s (%s) not recognized by stub"),
1211 config->name, config->title);
1213 case PACKET_SUPPORT_UNKNOWN:
1215 fprintf_unfiltered (gdb_stdlog,
1216 "Packet %s (%s) is NOT supported\n",
1217 config->name, config->title);
1218 config->support = PACKET_DISABLE;
1220 case PACKET_DISABLE:
1242 PACKET_vFile_pwrite,
1244 PACKET_vFile_unlink,
1245 PACKET_vFile_readlink,
1247 PACKET_qXfer_features,
1248 PACKET_qXfer_libraries,
1249 PACKET_qXfer_libraries_svr4,
1250 PACKET_qXfer_memory_map,
1251 PACKET_qXfer_spu_read,
1252 PACKET_qXfer_spu_write,
1253 PACKET_qXfer_osdata,
1254 PACKET_qXfer_threads,
1255 PACKET_qXfer_statictrace_read,
1256 PACKET_qXfer_traceframe_info,
1260 PACKET_QPassSignals,
1261 PACKET_qSearch_memory,
1264 PACKET_QStartNoAckMode,
1266 PACKET_qXfer_siginfo_read,
1267 PACKET_qXfer_siginfo_write,
1269 PACKET_ConditionalTracepoints,
1270 PACKET_ConditionalBreakpoints,
1271 PACKET_FastTracepoints,
1272 PACKET_StaticTracepoints,
1273 PACKET_InstallInTrace,
1276 PACKET_TracepointSource,
1279 PACKET_QDisableRandomization,
1284 static struct packet_config remote_protocol_packets[PACKET_MAX];
1287 set_remote_protocol_packet_cmd (char *args, int from_tty,
1288 struct cmd_list_element *c)
1290 struct packet_config *packet;
1292 for (packet = remote_protocol_packets;
1293 packet < &remote_protocol_packets[PACKET_MAX];
1296 if (&packet->detect == c->var)
1298 update_packet_config (packet);
1302 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1307 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1308 struct cmd_list_element *c,
1311 struct packet_config *packet;
1313 for (packet = remote_protocol_packets;
1314 packet < &remote_protocol_packets[PACKET_MAX];
1317 if (&packet->detect == c->var)
1319 show_packet_config_cmd (packet);
1323 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1327 /* Should we try one of the 'Z' requests? */
1331 Z_PACKET_SOFTWARE_BP,
1332 Z_PACKET_HARDWARE_BP,
1339 /* For compatibility with older distributions. Provide a ``set remote
1340 Z-packet ...'' command that updates all the Z packet types. */
1342 static enum auto_boolean remote_Z_packet_detect;
1345 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1346 struct cmd_list_element *c)
1350 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1352 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1353 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1358 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1359 struct cmd_list_element *c,
1364 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1366 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1370 /* Should we try the 'ThreadInfo' query packet?
1372 This variable (NOT available to the user: auto-detect only!)
1373 determines whether GDB will use the new, simpler "ThreadInfo"
1374 query or the older, more complex syntax for thread queries.
1375 This is an auto-detect variable (set to true at each connect,
1376 and set to false when the target fails to recognize it). */
1378 static int use_threadinfo_query;
1379 static int use_threadextra_query;
1381 /* Tokens for use by the asynchronous signal handlers for SIGINT. */
1382 static struct async_signal_handler *sigint_remote_twice_token;
1383 static struct async_signal_handler *sigint_remote_token;
1386 /* Asynchronous signal handle registered as event loop source for
1387 when we have pending events ready to be passed to the core. */
1389 static struct async_event_handler *remote_async_inferior_event_token;
1391 /* Asynchronous signal handle registered as event loop source for when
1392 the remote sent us a %Stop notification. The registered callback
1393 will do a vStopped sequence to pull the rest of the events out of
1394 the remote side into our event queue. */
1396 static struct async_event_handler *remote_async_get_pending_events_token;
1399 static ptid_t magic_null_ptid;
1400 static ptid_t not_sent_ptid;
1401 static ptid_t any_thread_ptid;
1403 /* These are the threads which we last sent to the remote system. The
1404 TID member will be -1 for all or -2 for not sent yet. */
1406 static ptid_t general_thread;
1407 static ptid_t continue_thread;
1409 /* This the traceframe which we last selected on the remote system.
1410 It will be -1 if no traceframe is selected. */
1411 static int remote_traceframe_number = -1;
1413 /* Find out if the stub attached to PID (and hence GDB should offer to
1414 detach instead of killing it when bailing out). */
1417 remote_query_attached (int pid)
1419 struct remote_state *rs = get_remote_state ();
1421 if (remote_protocol_packets[PACKET_qAttached].support == PACKET_DISABLE)
1424 if (remote_multi_process_p (rs))
1425 sprintf (rs->buf, "qAttached:%x", pid);
1427 sprintf (rs->buf, "qAttached");
1430 getpkt (&rs->buf, &rs->buf_size, 0);
1432 switch (packet_ok (rs->buf,
1433 &remote_protocol_packets[PACKET_qAttached]))
1436 if (strcmp (rs->buf, "1") == 0)
1440 warning (_("Remote failure reply: %s"), rs->buf);
1442 case PACKET_UNKNOWN:
1449 /* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1450 has been invented by GDB, instead of reported by the target. Since
1451 we can be connected to a remote system before before knowing about
1452 any inferior, mark the target with execution when we find the first
1453 inferior. If ATTACHED is 1, then we had just attached to this
1454 inferior. If it is 0, then we just created this inferior. If it
1455 is -1, then try querying the remote stub to find out if it had
1456 attached to the inferior or not. */
1458 static struct inferior *
1459 remote_add_inferior (int fake_pid_p, int pid, int attached)
1461 struct inferior *inf;
1463 /* Check whether this process we're learning about is to be
1464 considered attached, or if is to be considered to have been
1465 spawned by the stub. */
1467 attached = remote_query_attached (pid);
1469 if (gdbarch_has_global_solist (target_gdbarch))
1471 /* If the target shares code across all inferiors, then every
1472 attach adds a new inferior. */
1473 inf = add_inferior (pid);
1475 /* ... and every inferior is bound to the same program space.
1476 However, each inferior may still have its own address
1478 inf->aspace = maybe_new_address_space ();
1479 inf->pspace = current_program_space;
1483 /* In the traditional debugging scenario, there's a 1-1 match
1484 between program/address spaces. We simply bind the inferior
1485 to the program space's address space. */
1486 inf = current_inferior ();
1487 inferior_appeared (inf, pid);
1490 inf->attach_flag = attached;
1491 inf->fake_pid_p = fake_pid_p;
1496 /* Add thread PTID to GDB's thread list. Tag it as executing/running
1497 according to RUNNING. */
1500 remote_add_thread (ptid_t ptid, int running)
1504 set_executing (ptid, running);
1505 set_running (ptid, running);
1508 /* Come here when we learn about a thread id from the remote target.
1509 It may be the first time we hear about such thread, so take the
1510 opportunity to add it to GDB's thread list. In case this is the
1511 first time we're noticing its corresponding inferior, add it to
1512 GDB's inferior list as well. */
1515 remote_notice_new_inferior (ptid_t currthread, int running)
1517 /* If this is a new thread, add it to GDB's thread list.
1518 If we leave it up to WFI to do this, bad things will happen. */
1520 if (in_thread_list (currthread) && is_exited (currthread))
1522 /* We're seeing an event on a thread id we knew had exited.
1523 This has to be a new thread reusing the old id. Add it. */
1524 remote_add_thread (currthread, running);
1528 if (!in_thread_list (currthread))
1530 struct inferior *inf = NULL;
1531 int pid = ptid_get_pid (currthread);
1533 if (ptid_is_pid (inferior_ptid)
1534 && pid == ptid_get_pid (inferior_ptid))
1536 /* inferior_ptid has no thread member yet. This can happen
1537 with the vAttach -> remote_wait,"TAAthread:" path if the
1538 stub doesn't support qC. This is the first stop reported
1539 after an attach, so this is the main thread. Update the
1540 ptid in the thread list. */
1541 if (in_thread_list (pid_to_ptid (pid)))
1542 thread_change_ptid (inferior_ptid, currthread);
1545 remote_add_thread (currthread, running);
1546 inferior_ptid = currthread;
1551 if (ptid_equal (magic_null_ptid, inferior_ptid))
1553 /* inferior_ptid is not set yet. This can happen with the
1554 vRun -> remote_wait,"TAAthread:" path if the stub
1555 doesn't support qC. This is the first stop reported
1556 after an attach, so this is the main thread. Update the
1557 ptid in the thread list. */
1558 thread_change_ptid (inferior_ptid, currthread);
1562 /* When connecting to a target remote, or to a target
1563 extended-remote which already was debugging an inferior, we
1564 may not know about it yet. Add it before adding its child
1565 thread, so notifications are emitted in a sensible order. */
1566 if (!in_inferior_list (ptid_get_pid (currthread)))
1568 struct remote_state *rs = get_remote_state ();
1569 int fake_pid_p = !remote_multi_process_p (rs);
1571 inf = remote_add_inferior (fake_pid_p,
1572 ptid_get_pid (currthread), -1);
1575 /* This is really a new thread. Add it. */
1576 remote_add_thread (currthread, running);
1578 /* If we found a new inferior, let the common code do whatever
1579 it needs to with it (e.g., read shared libraries, insert
1582 notice_new_inferior (currthread, running, 0);
1586 /* Return the private thread data, creating it if necessary. */
1588 static struct private_thread_info *
1589 demand_private_info (ptid_t ptid)
1591 struct thread_info *info = find_thread_ptid (ptid);
1597 info->private = xmalloc (sizeof (*(info->private)));
1598 info->private_dtor = free_private_thread_info;
1599 info->private->core = -1;
1600 info->private->extra = 0;
1603 return info->private;
1606 /* Call this function as a result of
1607 1) A halt indication (T packet) containing a thread id
1608 2) A direct query of currthread
1609 3) Successful execution of set thread */
1612 record_currthread (ptid_t currthread)
1614 general_thread = currthread;
1617 static char *last_pass_packet;
1619 /* If 'QPassSignals' is supported, tell the remote stub what signals
1620 it can simply pass through to the inferior without reporting. */
1623 remote_pass_signals (int numsigs, unsigned char *pass_signals)
1625 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1627 char *pass_packet, *p;
1630 gdb_assert (numsigs < 256);
1631 for (i = 0; i < numsigs; i++)
1633 if (pass_signals[i])
1636 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1637 strcpy (pass_packet, "QPassSignals:");
1638 p = pass_packet + strlen (pass_packet);
1639 for (i = 0; i < numsigs; i++)
1641 if (pass_signals[i])
1644 *p++ = tohex (i >> 4);
1645 *p++ = tohex (i & 15);
1654 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1656 struct remote_state *rs = get_remote_state ();
1657 char *buf = rs->buf;
1659 putpkt (pass_packet);
1660 getpkt (&rs->buf, &rs->buf_size, 0);
1661 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1662 if (last_pass_packet)
1663 xfree (last_pass_packet);
1664 last_pass_packet = pass_packet;
1667 xfree (pass_packet);
1671 /* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1672 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1673 thread. If GEN is set, set the general thread, if not, then set
1674 the step/continue thread. */
1676 set_thread (struct ptid ptid, int gen)
1678 struct remote_state *rs = get_remote_state ();
1679 ptid_t state = gen ? general_thread : continue_thread;
1680 char *buf = rs->buf;
1681 char *endbuf = rs->buf + get_remote_packet_size ();
1683 if (ptid_equal (state, ptid))
1687 *buf++ = gen ? 'g' : 'c';
1688 if (ptid_equal (ptid, magic_null_ptid))
1689 xsnprintf (buf, endbuf - buf, "0");
1690 else if (ptid_equal (ptid, any_thread_ptid))
1691 xsnprintf (buf, endbuf - buf, "0");
1692 else if (ptid_equal (ptid, minus_one_ptid))
1693 xsnprintf (buf, endbuf - buf, "-1");
1695 write_ptid (buf, endbuf, ptid);
1697 getpkt (&rs->buf, &rs->buf_size, 0);
1699 general_thread = ptid;
1701 continue_thread = ptid;
1705 set_general_thread (struct ptid ptid)
1707 set_thread (ptid, 1);
1711 set_continue_thread (struct ptid ptid)
1713 set_thread (ptid, 0);
1716 /* Change the remote current process. Which thread within the process
1717 ends up selected isn't important, as long as it is the same process
1718 as what INFERIOR_PTID points to.
1720 This comes from that fact that there is no explicit notion of
1721 "selected process" in the protocol. The selected process for
1722 general operations is the process the selected general thread
1726 set_general_process (void)
1728 struct remote_state *rs = get_remote_state ();
1730 /* If the remote can't handle multiple processes, don't bother. */
1731 if (!rs->extended || !remote_multi_process_p (rs))
1734 /* We only need to change the remote current thread if it's pointing
1735 at some other process. */
1736 if (ptid_get_pid (general_thread) != ptid_get_pid (inferior_ptid))
1737 set_general_thread (inferior_ptid);
1741 /* Return nonzero if the thread PTID is still alive on the remote
1745 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1747 struct remote_state *rs = get_remote_state ();
1750 if (ptid_equal (ptid, magic_null_ptid))
1751 /* The main thread is always alive. */
1754 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1755 /* The main thread is always alive. This can happen after a
1756 vAttach, if the remote side doesn't support
1761 endp = rs->buf + get_remote_packet_size ();
1764 write_ptid (p, endp, ptid);
1767 getpkt (&rs->buf, &rs->buf_size, 0);
1768 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1771 /* About these extended threadlist and threadinfo packets. They are
1772 variable length packets but, the fields within them are often fixed
1773 length. They are redundent enough to send over UDP as is the
1774 remote protocol in general. There is a matching unit test module
1777 #define OPAQUETHREADBYTES 8
1779 /* a 64 bit opaque identifier */
1780 typedef unsigned char threadref[OPAQUETHREADBYTES];
1782 /* WARNING: This threadref data structure comes from the remote O.S.,
1783 libstub protocol encoding, and remote.c. It is not particularly
1786 /* Right now, the internal structure is int. We want it to be bigger.
1787 Plan to fix this. */
1789 typedef int gdb_threadref; /* Internal GDB thread reference. */
1791 /* gdb_ext_thread_info is an internal GDB data structure which is
1792 equivalent to the reply of the remote threadinfo packet. */
1794 struct gdb_ext_thread_info
1796 threadref threadid; /* External form of thread reference. */
1797 int active; /* Has state interesting to GDB?
1799 char display[256]; /* Brief state display, name,
1800 blocked/suspended. */
1801 char shortname[32]; /* To be used to name threads. */
1802 char more_display[256]; /* Long info, statistics, queue depth,
1806 /* The volume of remote transfers can be limited by submitting
1807 a mask containing bits specifying the desired information.
1808 Use a union of these values as the 'selection' parameter to
1809 get_thread_info. FIXME: Make these TAG names more thread specific. */
1811 #define TAG_THREADID 1
1812 #define TAG_EXISTS 2
1813 #define TAG_DISPLAY 4
1814 #define TAG_THREADNAME 8
1815 #define TAG_MOREDISPLAY 16
1817 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1819 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1821 static char *unpack_nibble (char *buf, int *val);
1823 static char *pack_nibble (char *buf, int nibble);
1825 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1827 static char *unpack_byte (char *buf, int *value);
1829 static char *pack_int (char *buf, int value);
1831 static char *unpack_int (char *buf, int *value);
1833 static char *unpack_string (char *src, char *dest, int length);
1835 static char *pack_threadid (char *pkt, threadref *id);
1837 static char *unpack_threadid (char *inbuf, threadref *id);
1839 void int_to_threadref (threadref *id, int value);
1841 static int threadref_to_int (threadref *ref);
1843 static void copy_threadref (threadref *dest, threadref *src);
1845 static int threadmatch (threadref *dest, threadref *src);
1847 static char *pack_threadinfo_request (char *pkt, int mode,
1850 static int remote_unpack_thread_info_response (char *pkt,
1851 threadref *expectedref,
1852 struct gdb_ext_thread_info
1856 static int remote_get_threadinfo (threadref *threadid,
1857 int fieldset, /*TAG mask */
1858 struct gdb_ext_thread_info *info);
1860 static char *pack_threadlist_request (char *pkt, int startflag,
1862 threadref *nextthread);
1864 static int parse_threadlist_response (char *pkt,
1866 threadref *original_echo,
1867 threadref *resultlist,
1870 static int remote_get_threadlist (int startflag,
1871 threadref *nextthread,
1875 threadref *threadlist);
1877 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1879 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1880 void *context, int looplimit);
1882 static int remote_newthread_step (threadref *ref, void *context);
1885 /* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
1886 buffer we're allowed to write to. Returns
1887 BUF+CHARACTERS_WRITTEN. */
1890 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
1893 struct remote_state *rs = get_remote_state ();
1895 if (remote_multi_process_p (rs))
1897 pid = ptid_get_pid (ptid);
1899 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
1901 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
1903 tid = ptid_get_tid (ptid);
1905 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
1907 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
1912 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
1913 passed the last parsed char. Returns null_ptid on error. */
1916 read_ptid (char *buf, char **obuf)
1920 ULONGEST pid = 0, tid = 0;
1924 /* Multi-process ptid. */
1925 pp = unpack_varlen_hex (p + 1, &pid);
1927 error (_("invalid remote ptid: %s"), p);
1930 pp = unpack_varlen_hex (p + 1, &tid);
1933 return ptid_build (pid, 0, tid);
1936 /* No multi-process. Just a tid. */
1937 pp = unpack_varlen_hex (p, &tid);
1939 /* Since the stub is not sending a process id, then default to
1940 what's in inferior_ptid, unless it's null at this point. If so,
1941 then since there's no way to know the pid of the reported
1942 threads, use the magic number. */
1943 if (ptid_equal (inferior_ptid, null_ptid))
1944 pid = ptid_get_pid (magic_null_ptid);
1946 pid = ptid_get_pid (inferior_ptid);
1950 return ptid_build (pid, 0, tid);
1953 /* Encode 64 bits in 16 chars of hex. */
1955 static const char hexchars[] = "0123456789abcdef";
1958 ishex (int ch, int *val)
1960 if ((ch >= 'a') && (ch <= 'f'))
1962 *val = ch - 'a' + 10;
1965 if ((ch >= 'A') && (ch <= 'F'))
1967 *val = ch - 'A' + 10;
1970 if ((ch >= '0') && (ch <= '9'))
1981 if (ch >= 'a' && ch <= 'f')
1982 return ch - 'a' + 10;
1983 if (ch >= '0' && ch <= '9')
1985 if (ch >= 'A' && ch <= 'F')
1986 return ch - 'A' + 10;
1991 stub_unpack_int (char *buff, int fieldlength)
1998 nibble = stubhex (*buff++);
2002 retval = retval << 4;
2008 unpack_varlen_hex (char *buff, /* packet to parse */
2012 ULONGEST retval = 0;
2014 while (ishex (*buff, &nibble))
2017 retval = retval << 4;
2018 retval |= nibble & 0x0f;
2025 unpack_nibble (char *buf, int *val)
2027 *val = fromhex (*buf++);
2032 pack_nibble (char *buf, int nibble)
2034 *buf++ = hexchars[(nibble & 0x0f)];
2039 pack_hex_byte (char *pkt, int byte)
2041 *pkt++ = hexchars[(byte >> 4) & 0xf];
2042 *pkt++ = hexchars[(byte & 0xf)];
2047 unpack_byte (char *buf, int *value)
2049 *value = stub_unpack_int (buf, 2);
2054 pack_int (char *buf, int value)
2056 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2057 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2058 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2059 buf = pack_hex_byte (buf, (value & 0xff));
2064 unpack_int (char *buf, int *value)
2066 *value = stub_unpack_int (buf, 8);
2070 #if 0 /* Currently unused, uncomment when needed. */
2071 static char *pack_string (char *pkt, char *string);
2074 pack_string (char *pkt, char *string)
2079 len = strlen (string);
2081 len = 200; /* Bigger than most GDB packets, junk??? */
2082 pkt = pack_hex_byte (pkt, len);
2086 if ((ch == '\0') || (ch == '#'))
2087 ch = '*'; /* Protect encapsulation. */
2092 #endif /* 0 (unused) */
2095 unpack_string (char *src, char *dest, int length)
2104 pack_threadid (char *pkt, threadref *id)
2107 unsigned char *altid;
2109 altid = (unsigned char *) id;
2110 limit = pkt + BUF_THREAD_ID_SIZE;
2112 pkt = pack_hex_byte (pkt, *altid++);
2118 unpack_threadid (char *inbuf, threadref *id)
2121 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2124 altref = (char *) id;
2126 while (inbuf < limit)
2128 x = stubhex (*inbuf++);
2129 y = stubhex (*inbuf++);
2130 *altref++ = (x << 4) | y;
2135 /* Externally, threadrefs are 64 bits but internally, they are still
2136 ints. This is due to a mismatch of specifications. We would like
2137 to use 64bit thread references internally. This is an adapter
2141 int_to_threadref (threadref *id, int value)
2143 unsigned char *scan;
2145 scan = (unsigned char *) id;
2151 *scan++ = (value >> 24) & 0xff;
2152 *scan++ = (value >> 16) & 0xff;
2153 *scan++ = (value >> 8) & 0xff;
2154 *scan++ = (value & 0xff);
2158 threadref_to_int (threadref *ref)
2161 unsigned char *scan;
2167 value = (value << 8) | ((*scan++) & 0xff);
2172 copy_threadref (threadref *dest, threadref *src)
2175 unsigned char *csrc, *cdest;
2177 csrc = (unsigned char *) src;
2178 cdest = (unsigned char *) dest;
2185 threadmatch (threadref *dest, threadref *src)
2187 /* Things are broken right now, so just assume we got a match. */
2189 unsigned char *srcp, *destp;
2191 srcp = (char *) src;
2192 destp = (char *) dest;
2196 result &= (*srcp++ == *destp++) ? 1 : 0;
2203 threadid:1, # always request threadid
2210 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2213 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2215 *pkt++ = 'q'; /* Info Query */
2216 *pkt++ = 'P'; /* process or thread info */
2217 pkt = pack_int (pkt, mode); /* mode */
2218 pkt = pack_threadid (pkt, id); /* threadid */
2219 *pkt = '\0'; /* terminate */
2223 /* These values tag the fields in a thread info response packet. */
2224 /* Tagging the fields allows us to request specific fields and to
2225 add more fields as time goes by. */
2227 #define TAG_THREADID 1 /* Echo the thread identifier. */
2228 #define TAG_EXISTS 2 /* Is this process defined enough to
2229 fetch registers and its stack? */
2230 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
2231 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
2232 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
2236 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2237 struct gdb_ext_thread_info *info)
2239 struct remote_state *rs = get_remote_state ();
2243 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
2246 /* info->threadid = 0; FIXME: implement zero_threadref. */
2248 info->display[0] = '\0';
2249 info->shortname[0] = '\0';
2250 info->more_display[0] = '\0';
2252 /* Assume the characters indicating the packet type have been
2254 pkt = unpack_int (pkt, &mask); /* arg mask */
2255 pkt = unpack_threadid (pkt, &ref);
2258 warning (_("Incomplete response to threadinfo request."));
2259 if (!threadmatch (&ref, expectedref))
2260 { /* This is an answer to a different request. */
2261 warning (_("ERROR RMT Thread info mismatch."));
2264 copy_threadref (&info->threadid, &ref);
2266 /* Loop on tagged fields , try to bail if somthing goes wrong. */
2268 /* Packets are terminated with nulls. */
2269 while ((pkt < limit) && mask && *pkt)
2271 pkt = unpack_int (pkt, &tag); /* tag */
2272 pkt = unpack_byte (pkt, &length); /* length */
2273 if (!(tag & mask)) /* Tags out of synch with mask. */
2275 warning (_("ERROR RMT: threadinfo tag mismatch."));
2279 if (tag == TAG_THREADID)
2283 warning (_("ERROR RMT: length of threadid is not 16."));
2287 pkt = unpack_threadid (pkt, &ref);
2288 mask = mask & ~TAG_THREADID;
2291 if (tag == TAG_EXISTS)
2293 info->active = stub_unpack_int (pkt, length);
2295 mask = mask & ~(TAG_EXISTS);
2298 warning (_("ERROR RMT: 'exists' length too long."));
2304 if (tag == TAG_THREADNAME)
2306 pkt = unpack_string (pkt, &info->shortname[0], length);
2307 mask = mask & ~TAG_THREADNAME;
2310 if (tag == TAG_DISPLAY)
2312 pkt = unpack_string (pkt, &info->display[0], length);
2313 mask = mask & ~TAG_DISPLAY;
2316 if (tag == TAG_MOREDISPLAY)
2318 pkt = unpack_string (pkt, &info->more_display[0], length);
2319 mask = mask & ~TAG_MOREDISPLAY;
2322 warning (_("ERROR RMT: unknown thread info tag."));
2323 break; /* Not a tag we know about. */
2329 remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2330 struct gdb_ext_thread_info *info)
2332 struct remote_state *rs = get_remote_state ();
2335 pack_threadinfo_request (rs->buf, fieldset, threadid);
2337 getpkt (&rs->buf, &rs->buf_size, 0);
2339 if (rs->buf[0] == '\0')
2342 result = remote_unpack_thread_info_response (rs->buf + 2,
2347 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2350 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2351 threadref *nextthread)
2353 *pkt++ = 'q'; /* info query packet */
2354 *pkt++ = 'L'; /* Process LIST or threadLIST request */
2355 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
2356 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2357 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2362 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2365 parse_threadlist_response (char *pkt, int result_limit,
2366 threadref *original_echo, threadref *resultlist,
2369 struct remote_state *rs = get_remote_state ();
2371 int count, resultcount, done;
2374 /* Assume the 'q' and 'M chars have been stripped. */
2375 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2376 /* done parse past here */
2377 pkt = unpack_byte (pkt, &count); /* count field */
2378 pkt = unpack_nibble (pkt, &done);
2379 /* The first threadid is the argument threadid. */
2380 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2381 while ((count-- > 0) && (pkt < limit))
2383 pkt = unpack_threadid (pkt, resultlist++);
2384 if (resultcount++ >= result_limit)
2393 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2394 int *done, int *result_count, threadref *threadlist)
2396 struct remote_state *rs = get_remote_state ();
2397 static threadref echo_nextthread;
2400 /* Trancate result limit to be smaller than the packet size. */
2401 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2402 >= get_remote_packet_size ())
2403 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2405 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2407 getpkt (&rs->buf, &rs->buf_size, 0);
2409 if (*rs->buf == '\0')
2413 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
2416 if (!threadmatch (&echo_nextthread, nextthread))
2418 /* FIXME: This is a good reason to drop the packet. */
2419 /* Possably, there is a duplicate response. */
2421 retransmit immediatly - race conditions
2422 retransmit after timeout - yes
2424 wait for packet, then exit
2426 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2427 return 0; /* I choose simply exiting. */
2429 if (*result_count <= 0)
2433 warning (_("RMT ERROR : failed to get remote thread list."));
2436 return result; /* break; */
2438 if (*result_count > result_limit)
2441 warning (_("RMT ERROR: threadlist response longer than requested."));
2447 /* This is the interface between remote and threads, remotes upper
2450 /* remote_find_new_threads retrieves the thread list and for each
2451 thread in the list, looks up the thread in GDB's internal list,
2452 adding the thread if it does not already exist. This involves
2453 getting partial thread lists from the remote target so, polling the
2454 quit_flag is required. */
2457 /* About this many threadisds fit in a packet. */
2459 #define MAXTHREADLISTRESULTS 32
2462 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2465 int done, i, result_count;
2469 static threadref nextthread;
2470 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
2475 if (loopcount++ > looplimit)
2478 warning (_("Remote fetch threadlist -infinite loop-."));
2481 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
2482 &done, &result_count, resultthreadlist))
2487 /* Clear for later iterations. */
2489 /* Setup to resume next batch of thread references, set nextthread. */
2490 if (result_count >= 1)
2491 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
2493 while (result_count--)
2494 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
2501 remote_newthread_step (threadref *ref, void *context)
2503 int pid = ptid_get_pid (inferior_ptid);
2504 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
2506 if (!in_thread_list (ptid))
2508 return 1; /* continue iterator */
2511 #define CRAZY_MAX_THREADS 1000
2514 remote_current_thread (ptid_t oldpid)
2516 struct remote_state *rs = get_remote_state ();
2519 getpkt (&rs->buf, &rs->buf_size, 0);
2520 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2521 return read_ptid (&rs->buf[2], NULL);
2526 /* Find new threads for info threads command.
2527 * Original version, using John Metzler's thread protocol.
2531 remote_find_new_threads (void)
2533 remote_threadlist_iterator (remote_newthread_step, 0,
2537 #if defined(HAVE_LIBEXPAT)
2539 typedef struct thread_item
2545 DEF_VEC_O(thread_item_t);
2547 struct threads_parsing_context
2549 VEC (thread_item_t) *items;
2553 start_thread (struct gdb_xml_parser *parser,
2554 const struct gdb_xml_element *element,
2555 void *user_data, VEC(gdb_xml_value_s) *attributes)
2557 struct threads_parsing_context *data = user_data;
2559 struct thread_item item;
2561 struct gdb_xml_value *attr;
2563 id = xml_find_attribute (attributes, "id")->value;
2564 item.ptid = read_ptid (id, NULL);
2566 attr = xml_find_attribute (attributes, "core");
2568 item.core = *(ULONGEST *) attr->value;
2574 VEC_safe_push (thread_item_t, data->items, &item);
2578 end_thread (struct gdb_xml_parser *parser,
2579 const struct gdb_xml_element *element,
2580 void *user_data, const char *body_text)
2582 struct threads_parsing_context *data = user_data;
2584 if (body_text && *body_text)
2585 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2588 const struct gdb_xml_attribute thread_attributes[] = {
2589 { "id", GDB_XML_AF_NONE, NULL, NULL },
2590 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2591 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2594 const struct gdb_xml_element thread_children[] = {
2595 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2598 const struct gdb_xml_element threads_children[] = {
2599 { "thread", thread_attributes, thread_children,
2600 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2601 start_thread, end_thread },
2602 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2605 const struct gdb_xml_element threads_elements[] = {
2606 { "threads", NULL, threads_children,
2607 GDB_XML_EF_NONE, NULL, NULL },
2608 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2611 /* Discard the contents of the constructed thread info context. */
2614 clear_threads_parsing_context (void *p)
2616 struct threads_parsing_context *context = p;
2618 struct thread_item *item;
2620 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2621 xfree (item->extra);
2623 VEC_free (thread_item_t, context->items);
2629 * Find all threads for info threads command.
2630 * Uses new thread protocol contributed by Cisco.
2631 * Falls back and attempts to use the older method (above)
2632 * if the target doesn't respond to the new method.
2636 remote_threads_info (struct target_ops *ops)
2638 struct remote_state *rs = get_remote_state ();
2642 if (remote_desc == 0) /* paranoia */
2643 error (_("Command can only be used when connected to the remote target."));
2645 #if defined(HAVE_LIBEXPAT)
2646 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2648 char *xml = target_read_stralloc (¤t_target,
2649 TARGET_OBJECT_THREADS, NULL);
2651 struct cleanup *back_to = make_cleanup (xfree, xml);
2655 struct threads_parsing_context context;
2657 context.items = NULL;
2658 make_cleanup (clear_threads_parsing_context, &context);
2660 if (gdb_xml_parse_quick (_("threads"), "threads.dtd",
2661 threads_elements, xml, &context) == 0)
2664 struct thread_item *item;
2667 VEC_iterate (thread_item_t, context.items, i, item);
2670 if (!ptid_equal (item->ptid, null_ptid))
2672 struct private_thread_info *info;
2673 /* In non-stop mode, we assume new found threads
2674 are running until proven otherwise with a
2675 stop reply. In all-stop, we can only get
2676 here if all threads are stopped. */
2677 int running = non_stop ? 1 : 0;
2679 remote_notice_new_inferior (item->ptid, running);
2681 info = demand_private_info (item->ptid);
2682 info->core = item->core;
2683 info->extra = item->extra;
2690 do_cleanups (back_to);
2695 if (use_threadinfo_query)
2697 putpkt ("qfThreadInfo");
2698 getpkt (&rs->buf, &rs->buf_size, 0);
2700 if (bufp[0] != '\0') /* q packet recognized */
2702 while (*bufp++ == 'm') /* reply contains one or more TID */
2706 new_thread = read_ptid (bufp, &bufp);
2707 if (!ptid_equal (new_thread, null_ptid))
2709 /* In non-stop mode, we assume new found threads
2710 are running until proven otherwise with a
2711 stop reply. In all-stop, we can only get
2712 here if all threads are stopped. */
2713 int running = non_stop ? 1 : 0;
2715 remote_notice_new_inferior (new_thread, running);
2718 while (*bufp++ == ','); /* comma-separated list */
2719 putpkt ("qsThreadInfo");
2720 getpkt (&rs->buf, &rs->buf_size, 0);
2727 /* Only qfThreadInfo is supported in non-stop mode. */
2731 /* Else fall back to old method based on jmetzler protocol. */
2732 use_threadinfo_query = 0;
2733 remote_find_new_threads ();
2738 * Collect a descriptive string about the given thread.
2739 * The target may say anything it wants to about the thread
2740 * (typically info about its blocked / runnable state, name, etc.).
2741 * This string will appear in the info threads display.
2743 * Optional: targets are not required to implement this function.
2747 remote_threads_extra_info (struct thread_info *tp)
2749 struct remote_state *rs = get_remote_state ();
2753 struct gdb_ext_thread_info threadinfo;
2754 static char display_buf[100]; /* arbitrary... */
2755 int n = 0; /* position in display_buf */
2757 if (remote_desc == 0) /* paranoia */
2758 internal_error (__FILE__, __LINE__,
2759 _("remote_threads_extra_info"));
2761 if (ptid_equal (tp->ptid, magic_null_ptid)
2762 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2763 /* This is the main thread which was added by GDB. The remote
2764 server doesn't know about it. */
2767 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2769 struct thread_info *info = find_thread_ptid (tp->ptid);
2771 if (info && info->private)
2772 return info->private->extra;
2777 if (use_threadextra_query)
2780 char *endb = rs->buf + get_remote_packet_size ();
2782 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2784 write_ptid (b, endb, tp->ptid);
2787 getpkt (&rs->buf, &rs->buf_size, 0);
2788 if (rs->buf[0] != 0)
2790 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2791 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2792 display_buf [result] = '\0';
2797 /* If the above query fails, fall back to the old method. */
2798 use_threadextra_query = 0;
2799 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2800 | TAG_MOREDISPLAY | TAG_DISPLAY;
2801 int_to_threadref (&id, ptid_get_tid (tp->ptid));
2802 if (remote_get_threadinfo (&id, set, &threadinfo))
2803 if (threadinfo.active)
2805 if (*threadinfo.shortname)
2806 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2807 " Name: %s,", threadinfo.shortname);
2808 if (*threadinfo.display)
2809 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2810 " State: %s,", threadinfo.display);
2811 if (*threadinfo.more_display)
2812 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2813 " Priority: %s", threadinfo.more_display);
2817 /* For purely cosmetic reasons, clear up trailing commas. */
2818 if (',' == display_buf[n-1])
2819 display_buf[n-1] = ' ';
2828 remote_static_tracepoint_marker_at (CORE_ADDR addr,
2829 struct static_tracepoint_marker *marker)
2831 struct remote_state *rs = get_remote_state ();
2834 sprintf (p, "qTSTMat:");
2836 p += hexnumstr (p, addr);
2838 getpkt (&rs->buf, &rs->buf_size, 0);
2842 error (_("Remote failure reply: %s"), p);
2846 parse_static_tracepoint_marker_definition (p, &p, marker);
2854 free_current_marker (void *arg)
2856 struct static_tracepoint_marker **marker_p = arg;
2858 if (*marker_p != NULL)
2860 release_static_tracepoint_marker (*marker_p);
2867 static VEC(static_tracepoint_marker_p) *
2868 remote_static_tracepoint_markers_by_strid (const char *strid)
2870 struct remote_state *rs = get_remote_state ();
2871 VEC(static_tracepoint_marker_p) *markers = NULL;
2872 struct static_tracepoint_marker *marker = NULL;
2873 struct cleanup *old_chain;
2876 /* Ask for a first packet of static tracepoint marker
2879 getpkt (&rs->buf, &rs->buf_size, 0);
2882 error (_("Remote failure reply: %s"), p);
2884 old_chain = make_cleanup (free_current_marker, &marker);
2889 marker = XCNEW (struct static_tracepoint_marker);
2893 parse_static_tracepoint_marker_definition (p, &p, marker);
2895 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
2897 VEC_safe_push (static_tracepoint_marker_p,
2903 release_static_tracepoint_marker (marker);
2904 memset (marker, 0, sizeof (*marker));
2907 while (*p++ == ','); /* comma-separated list */
2908 /* Ask for another packet of static tracepoint definition. */
2910 getpkt (&rs->buf, &rs->buf_size, 0);
2914 do_cleanups (old_chain);
2919 /* Implement the to_get_ada_task_ptid function for the remote targets. */
2922 remote_get_ada_task_ptid (long lwp, long thread)
2924 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
2928 /* Restart the remote side; this is an extended protocol operation. */
2931 extended_remote_restart (void)
2933 struct remote_state *rs = get_remote_state ();
2935 /* Send the restart command; for reasons I don't understand the
2936 remote side really expects a number after the "R". */
2937 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
2940 remote_fileio_reset ();
2943 /* Clean up connection to a remote debugger. */
2946 remote_close (int quitting)
2948 if (remote_desc == NULL)
2949 return; /* already closed */
2951 /* Make sure we leave stdin registered in the event loop, and we
2952 don't leave the async SIGINT signal handler installed. */
2953 remote_terminal_ours ();
2955 serial_close (remote_desc);
2958 /* We don't have a connection to the remote stub anymore. Get rid
2959 of all the inferiors and their threads we were controlling.
2960 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
2961 will be unable to find the thread corresponding to (pid, 0, 0). */
2962 inferior_ptid = null_ptid;
2963 discard_all_inferiors ();
2965 /* We're no longer interested in any of these events. */
2966 discard_pending_stop_replies (-1);
2968 if (remote_async_inferior_event_token)
2969 delete_async_event_handler (&remote_async_inferior_event_token);
2970 if (remote_async_get_pending_events_token)
2971 delete_async_event_handler (&remote_async_get_pending_events_token);
2974 /* Query the remote side for the text, data and bss offsets. */
2979 struct remote_state *rs = get_remote_state ();
2982 int lose, num_segments = 0, do_sections, do_segments;
2983 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
2984 struct section_offsets *offs;
2985 struct symfile_segment_data *data;
2987 if (symfile_objfile == NULL)
2990 putpkt ("qOffsets");
2991 getpkt (&rs->buf, &rs->buf_size, 0);
2994 if (buf[0] == '\000')
2995 return; /* Return silently. Stub doesn't support
2999 warning (_("Remote failure reply: %s"), buf);
3003 /* Pick up each field in turn. This used to be done with scanf, but
3004 scanf will make trouble if CORE_ADDR size doesn't match
3005 conversion directives correctly. The following code will work
3006 with any size of CORE_ADDR. */
3007 text_addr = data_addr = bss_addr = 0;
3011 if (strncmp (ptr, "Text=", 5) == 0)
3014 /* Don't use strtol, could lose on big values. */
3015 while (*ptr && *ptr != ';')
3016 text_addr = (text_addr << 4) + fromhex (*ptr++);
3018 if (strncmp (ptr, ";Data=", 6) == 0)
3021 while (*ptr && *ptr != ';')
3022 data_addr = (data_addr << 4) + fromhex (*ptr++);
3027 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
3030 while (*ptr && *ptr != ';')
3031 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3033 if (bss_addr != data_addr)
3034 warning (_("Target reported unsupported offsets: %s"), buf);
3039 else if (strncmp (ptr, "TextSeg=", 8) == 0)
3042 /* Don't use strtol, could lose on big values. */
3043 while (*ptr && *ptr != ';')
3044 text_addr = (text_addr << 4) + fromhex (*ptr++);
3047 if (strncmp (ptr, ";DataSeg=", 9) == 0)
3050 while (*ptr && *ptr != ';')
3051 data_addr = (data_addr << 4) + fromhex (*ptr++);
3059 error (_("Malformed response to offset query, %s"), buf);
3060 else if (*ptr != '\0')
3061 warning (_("Target reported unsupported offsets: %s"), buf);
3063 offs = ((struct section_offsets *)
3064 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3065 memcpy (offs, symfile_objfile->section_offsets,
3066 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3068 data = get_symfile_segment_data (symfile_objfile->obfd);
3069 do_segments = (data != NULL);
3070 do_sections = num_segments == 0;
3072 if (num_segments > 0)
3074 segments[0] = text_addr;
3075 segments[1] = data_addr;
3077 /* If we have two segments, we can still try to relocate everything
3078 by assuming that the .text and .data offsets apply to the whole
3079 text and data segments. Convert the offsets given in the packet
3080 to base addresses for symfile_map_offsets_to_segments. */
3081 else if (data && data->num_segments == 2)
3083 segments[0] = data->segment_bases[0] + text_addr;
3084 segments[1] = data->segment_bases[1] + data_addr;
3087 /* If the object file has only one segment, assume that it is text
3088 rather than data; main programs with no writable data are rare,
3089 but programs with no code are useless. Of course the code might
3090 have ended up in the data segment... to detect that we would need
3091 the permissions here. */
3092 else if (data && data->num_segments == 1)
3094 segments[0] = data->segment_bases[0] + text_addr;
3097 /* There's no way to relocate by segment. */
3103 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3104 offs, num_segments, segments);
3106 if (ret == 0 && !do_sections)
3107 error (_("Can not handle qOffsets TextSeg "
3108 "response with this symbol file"));
3115 free_symfile_segment_data (data);
3119 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3121 /* This is a temporary kludge to force data and bss to use the
3122 same offsets because that's what nlmconv does now. The real
3123 solution requires changes to the stub and remote.c that I
3124 don't have time to do right now. */
3126 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3127 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3130 objfile_relocate (symfile_objfile, offs);
3133 /* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3134 threads we know are stopped already. This is used during the
3135 initial remote connection in non-stop mode --- threads that are
3136 reported as already being stopped are left stopped. */
3139 set_stop_requested_callback (struct thread_info *thread, void *data)
3141 /* If we have a stop reply for this thread, it must be stopped. */
3142 if (peek_stop_reply (thread->ptid))
3143 set_stop_requested (thread->ptid, 1);
3148 /* Send interrupt_sequence to remote target. */
3150 send_interrupt_sequence (void)
3152 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3153 serial_write (remote_desc, "\x03", 1);
3154 else if (interrupt_sequence_mode == interrupt_sequence_break)
3155 serial_send_break (remote_desc);
3156 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3158 serial_send_break (remote_desc);
3159 serial_write (remote_desc, "g", 1);
3162 internal_error (__FILE__, __LINE__,
3163 _("Invalid value for interrupt_sequence_mode: %s."),
3164 interrupt_sequence_mode);
3167 /* Query the remote target for which is the current thread/process,
3168 add it to our tables, and update INFERIOR_PTID. The caller is
3169 responsible for setting the state such that the remote end is ready
3170 to return the current thread. */
3173 add_current_inferior_and_thread (void)
3175 struct remote_state *rs = get_remote_state ();
3179 inferior_ptid = null_ptid;
3181 /* Now, if we have thread information, update inferior_ptid. */
3182 ptid = remote_current_thread (inferior_ptid);
3183 if (!ptid_equal (ptid, null_ptid))
3185 if (!remote_multi_process_p (rs))
3188 inferior_ptid = ptid;
3192 /* Without this, some commands which require an active target
3193 (such as kill) won't work. This variable serves (at least)
3194 double duty as both the pid of the target process (if it has
3195 such), and as a flag indicating that a target is active. */
3196 inferior_ptid = magic_null_ptid;
3200 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3202 /* Add the main thread. */
3203 add_thread_silent (inferior_ptid);
3207 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3209 struct remote_state *rs = get_remote_state ();
3210 struct packet_config *noack_config;
3211 char *wait_status = NULL;
3213 immediate_quit++; /* Allow user to interrupt it. */
3215 if (interrupt_on_connect)
3216 send_interrupt_sequence ();
3218 /* Ack any packet which the remote side has already sent. */
3219 serial_write (remote_desc, "+", 1);
3221 /* The first packet we send to the target is the optional "supported
3222 packets" request. If the target can answer this, it will tell us
3223 which later probes to skip. */
3224 remote_query_supported ();
3226 /* If the stub wants to get a QAllow, compose one and send it. */
3227 if (remote_protocol_packets[PACKET_QAllow].support != PACKET_DISABLE)
3228 remote_set_permissions ();
3230 /* Next, we possibly activate noack mode.
3232 If the QStartNoAckMode packet configuration is set to AUTO,
3233 enable noack mode if the stub reported a wish for it with
3236 If set to TRUE, then enable noack mode even if the stub didn't
3237 report it in qSupported. If the stub doesn't reply OK, the
3238 session ends with an error.
3240 If FALSE, then don't activate noack mode, regardless of what the
3241 stub claimed should be the default with qSupported. */
3243 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3245 if (noack_config->detect == AUTO_BOOLEAN_TRUE
3246 || (noack_config->detect == AUTO_BOOLEAN_AUTO
3247 && noack_config->support == PACKET_ENABLE))
3249 putpkt ("QStartNoAckMode");
3250 getpkt (&rs->buf, &rs->buf_size, 0);
3251 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3257 /* Tell the remote that we are using the extended protocol. */
3259 getpkt (&rs->buf, &rs->buf_size, 0);
3262 /* Next, if the target can specify a description, read it. We do
3263 this before anything involving memory or registers. */
3264 target_find_description ();
3266 /* Next, now that we know something about the target, update the
3267 address spaces in the program spaces. */
3268 update_address_spaces ();
3270 /* On OSs where the list of libraries is global to all
3271 processes, we fetch them early. */
3272 if (gdbarch_has_global_solist (target_gdbarch))
3273 solib_add (NULL, from_tty, target, auto_solib_add);
3277 if (!rs->non_stop_aware)
3278 error (_("Non-stop mode requested, but remote "
3279 "does not support non-stop"));
3281 putpkt ("QNonStop:1");
3282 getpkt (&rs->buf, &rs->buf_size, 0);
3284 if (strcmp (rs->buf, "OK") != 0)
3285 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3287 /* Find about threads and processes the stub is already
3288 controlling. We default to adding them in the running state.
3289 The '?' query below will then tell us about which threads are
3291 remote_threads_info (target);
3293 else if (rs->non_stop_aware)
3295 /* Don't assume that the stub can operate in all-stop mode.
3296 Request it explicitely. */
3297 putpkt ("QNonStop:0");
3298 getpkt (&rs->buf, &rs->buf_size, 0);
3300 if (strcmp (rs->buf, "OK") != 0)
3301 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3304 /* Check whether the target is running now. */
3306 getpkt (&rs->buf, &rs->buf_size, 0);
3312 struct inferior *inf;
3314 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3317 error (_("The target is not running (try extended-remote?)"));
3319 /* We're connected, but not running. Drop out before we
3320 call start_remote. */
3325 /* Save the reply for later. */
3326 wait_status = alloca (strlen (rs->buf) + 1);
3327 strcpy (wait_status, rs->buf);
3330 /* Let the stub know that we want it to return the thread. */
3331 set_continue_thread (minus_one_ptid);
3333 add_current_inferior_and_thread ();
3335 /* init_wait_for_inferior should be called before get_offsets in order
3336 to manage `inserted' flag in bp loc in a correct state.
3337 breakpoint_init_inferior, called from init_wait_for_inferior, set
3338 `inserted' flag to 0, while before breakpoint_re_set, called from
3339 start_remote, set `inserted' flag to 1. In the initialization of
3340 inferior, breakpoint_init_inferior should be called first, and then
3341 breakpoint_re_set can be called. If this order is broken, state of
3342 `inserted' flag is wrong, and cause some problems on breakpoint
3344 init_wait_for_inferior ();
3346 get_offsets (); /* Get text, data & bss offsets. */
3348 /* If we could not find a description using qXfer, and we know
3349 how to do it some other way, try again. This is not
3350 supported for non-stop; it could be, but it is tricky if
3351 there are no stopped threads when we connect. */
3352 if (remote_read_description_p (target)
3353 && gdbarch_target_desc (target_gdbarch) == NULL)
3355 target_clear_description ();
3356 target_find_description ();
3359 /* Use the previously fetched status. */
3360 gdb_assert (wait_status != NULL);
3361 strcpy (rs->buf, wait_status);
3362 rs->cached_wait_status = 1;
3365 start_remote (from_tty); /* Initialize gdb process mechanisms. */
3369 /* Clear WFI global state. Do this before finding about new
3370 threads and inferiors, and setting the current inferior.
3371 Otherwise we would clear the proceed status of the current
3372 inferior when we want its stop_soon state to be preserved
3373 (see notice_new_inferior). */
3374 init_wait_for_inferior ();
3376 /* In non-stop, we will either get an "OK", meaning that there
3377 are no stopped threads at this time; or, a regular stop
3378 reply. In the latter case, there may be more than one thread
3379 stopped --- we pull them all out using the vStopped
3381 if (strcmp (rs->buf, "OK") != 0)
3383 struct stop_reply *stop_reply;
3384 struct cleanup *old_chain;
3386 stop_reply = stop_reply_xmalloc ();
3387 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
3389 remote_parse_stop_reply (rs->buf, stop_reply);
3390 discard_cleanups (old_chain);
3392 /* get_pending_stop_replies acks this one, and gets the rest
3394 pending_stop_reply = stop_reply;
3395 remote_get_pending_stop_replies ();
3397 /* Make sure that threads that were stopped remain
3399 iterate_over_threads (set_stop_requested_callback, NULL);
3402 if (target_can_async_p ())
3403 target_async (inferior_event_handler, 0);
3405 if (thread_count () == 0)
3408 error (_("The target is not running (try extended-remote?)"));
3410 /* We're connected, but not running. Drop out before we
3411 call start_remote. */
3415 /* Let the stub know that we want it to return the thread. */
3417 /* Force the stub to choose a thread. */
3418 set_general_thread (null_ptid);
3421 inferior_ptid = remote_current_thread (minus_one_ptid);
3422 if (ptid_equal (inferior_ptid, minus_one_ptid))
3423 error (_("remote didn't report the current thread in non-stop mode"));
3425 get_offsets (); /* Get text, data & bss offsets. */
3427 /* In non-stop mode, any cached wait status will be stored in
3428 the stop reply queue. */
3429 gdb_assert (wait_status == NULL);
3431 /* Report all signals during attach/startup. */
3432 remote_pass_signals (0, NULL);
3435 /* If we connected to a live target, do some additional setup. */
3436 if (target_has_execution)
3438 if (exec_bfd) /* No use without an exec file. */
3439 remote_check_symbols (symfile_objfile);
3442 /* Possibly the target has been engaged in a trace run started
3443 previously; find out where things are at. */
3444 if (remote_get_trace_status (current_trace_status ()) != -1)
3446 struct uploaded_tp *uploaded_tps = NULL;
3447 struct uploaded_tsv *uploaded_tsvs = NULL;
3449 if (current_trace_status ()->running)
3450 printf_filtered (_("Trace is already running on the target.\n"));
3452 /* Get trace state variables first, they may be checked when
3453 parsing uploaded commands. */
3455 remote_upload_trace_state_variables (&uploaded_tsvs);
3457 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3459 remote_upload_tracepoints (&uploaded_tps);
3461 merge_uploaded_tracepoints (&uploaded_tps);
3464 /* If breakpoints are global, insert them now. */
3465 if (gdbarch_has_global_breakpoints (target_gdbarch)
3466 && breakpoints_always_inserted_mode ())
3467 insert_breakpoints ();
3470 /* Open a connection to a remote debugger.
3471 NAME is the filename used for communication. */
3474 remote_open (char *name, int from_tty)
3476 remote_open_1 (name, from_tty, &remote_ops, 0);
3479 /* Open a connection to a remote debugger using the extended
3480 remote gdb protocol. NAME is the filename used for communication. */
3483 extended_remote_open (char *name, int from_tty)
3485 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3488 /* Generic code for opening a connection to a remote target. */
3491 init_all_packet_configs (void)
3495 for (i = 0; i < PACKET_MAX; i++)
3496 update_packet_config (&remote_protocol_packets[i]);
3499 /* Symbol look-up. */
3502 remote_check_symbols (struct objfile *objfile)
3504 struct remote_state *rs = get_remote_state ();
3505 char *msg, *reply, *tmp;
3506 struct minimal_symbol *sym;
3509 /* The remote side has no concept of inferiors that aren't running
3510 yet, it only knows about running processes. If we're connected
3511 but our current inferior is not running, we should not invite the
3512 remote target to request symbol lookups related to its
3513 (unrelated) current process. */
3514 if (!target_has_execution)
3517 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
3520 /* Make sure the remote is pointing at the right process. Note
3521 there's no way to select "no process". */
3522 set_general_process ();
3524 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3525 because we need both at the same time. */
3526 msg = alloca (get_remote_packet_size ());
3528 /* Invite target to request symbol lookups. */
3530 putpkt ("qSymbol::");
3531 getpkt (&rs->buf, &rs->buf_size, 0);
3532 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3535 while (strncmp (reply, "qSymbol:", 8) == 0)
3538 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3540 sym = lookup_minimal_symbol (msg, NULL, NULL);
3542 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3545 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
3546 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
3548 /* If this is a function address, return the start of code
3549 instead of any data function descriptor. */
3550 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch,
3554 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3555 phex_nz (sym_addr, addr_size), &reply[8]);
3559 getpkt (&rs->buf, &rs->buf_size, 0);
3564 static struct serial *
3565 remote_serial_open (char *name)
3567 static int udp_warning = 0;
3569 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3570 of in ser-tcp.c, because it is the remote protocol assuming that the
3571 serial connection is reliable and not the serial connection promising
3573 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3575 warning (_("The remote protocol may be unreliable over UDP.\n"
3576 "Some events may be lost, rendering further debugging "
3581 return serial_open (name);
3584 /* Inform the target of our permission settings. The permission flags
3585 work without this, but if the target knows the settings, it can do
3586 a couple things. First, it can add its own check, to catch cases
3587 that somehow manage to get by the permissions checks in target
3588 methods. Second, if the target is wired to disallow particular
3589 settings (for instance, a system in the field that is not set up to
3590 be able to stop at a breakpoint), it can object to any unavailable
3594 remote_set_permissions (void)
3596 struct remote_state *rs = get_remote_state ();
3598 sprintf (rs->buf, "QAllow:"
3599 "WriteReg:%x;WriteMem:%x;"
3600 "InsertBreak:%x;InsertTrace:%x;"
3601 "InsertFastTrace:%x;Stop:%x",
3602 may_write_registers, may_write_memory,
3603 may_insert_breakpoints, may_insert_tracepoints,
3604 may_insert_fast_tracepoints, may_stop);
3606 getpkt (&rs->buf, &rs->buf_size, 0);
3608 /* If the target didn't like the packet, warn the user. Do not try
3609 to undo the user's settings, that would just be maddening. */
3610 if (strcmp (rs->buf, "OK") != 0)
3611 warning (_("Remote refused setting permissions with: %s"), rs->buf);
3614 /* This type describes each known response to the qSupported
3616 struct protocol_feature
3618 /* The name of this protocol feature. */
3621 /* The default for this protocol feature. */
3622 enum packet_support default_support;
3624 /* The function to call when this feature is reported, or after
3625 qSupported processing if the feature is not supported.
3626 The first argument points to this structure. The second
3627 argument indicates whether the packet requested support be
3628 enabled, disabled, or probed (or the default, if this function
3629 is being called at the end of processing and this feature was
3630 not reported). The third argument may be NULL; if not NULL, it
3631 is a NUL-terminated string taken from the packet following
3632 this feature's name and an equals sign. */
3633 void (*func) (const struct protocol_feature *, enum packet_support,
3636 /* The corresponding packet for this feature. Only used if
3637 FUNC is remote_supported_packet. */
3642 remote_supported_packet (const struct protocol_feature *feature,
3643 enum packet_support support,
3644 const char *argument)
3648 warning (_("Remote qSupported response supplied an unexpected value for"
3649 " \"%s\"."), feature->name);
3653 if (remote_protocol_packets[feature->packet].support
3654 == PACKET_SUPPORT_UNKNOWN)
3655 remote_protocol_packets[feature->packet].support = support;
3659 remote_packet_size (const struct protocol_feature *feature,
3660 enum packet_support support, const char *value)
3662 struct remote_state *rs = get_remote_state ();
3667 if (support != PACKET_ENABLE)
3670 if (value == NULL || *value == '\0')
3672 warning (_("Remote target reported \"%s\" without a size."),
3678 packet_size = strtol (value, &value_end, 16);
3679 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3681 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3682 feature->name, value);
3686 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3688 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3689 packet_size, MAX_REMOTE_PACKET_SIZE);
3690 packet_size = MAX_REMOTE_PACKET_SIZE;
3693 /* Record the new maximum packet size. */
3694 rs->explicit_packet_size = packet_size;
3698 remote_multi_process_feature (const struct protocol_feature *feature,
3699 enum packet_support support, const char *value)
3701 struct remote_state *rs = get_remote_state ();
3703 rs->multi_process_aware = (support == PACKET_ENABLE);
3707 remote_non_stop_feature (const struct protocol_feature *feature,
3708 enum packet_support support, const char *value)
3710 struct remote_state *rs = get_remote_state ();
3712 rs->non_stop_aware = (support == PACKET_ENABLE);
3716 remote_cond_tracepoint_feature (const struct protocol_feature *feature,
3717 enum packet_support support,
3720 struct remote_state *rs = get_remote_state ();
3722 rs->cond_tracepoints = (support == PACKET_ENABLE);
3726 remote_cond_breakpoint_feature (const struct protocol_feature *feature,
3727 enum packet_support support,
3730 struct remote_state *rs = get_remote_state ();
3732 rs->cond_breakpoints = (support == PACKET_ENABLE);
3736 remote_fast_tracepoint_feature (const struct protocol_feature *feature,
3737 enum packet_support support,
3740 struct remote_state *rs = get_remote_state ();
3742 rs->fast_tracepoints = (support == PACKET_ENABLE);
3746 remote_static_tracepoint_feature (const struct protocol_feature *feature,
3747 enum packet_support support,
3750 struct remote_state *rs = get_remote_state ();
3752 rs->static_tracepoints = (support == PACKET_ENABLE);
3756 remote_install_in_trace_feature (const struct protocol_feature *feature,
3757 enum packet_support support,
3760 struct remote_state *rs = get_remote_state ();
3762 rs->install_in_trace = (support == PACKET_ENABLE);
3766 remote_disconnected_tracing_feature (const struct protocol_feature *feature,
3767 enum packet_support support,
3770 struct remote_state *rs = get_remote_state ();
3772 rs->disconnected_tracing = (support == PACKET_ENABLE);
3776 remote_enable_disable_tracepoint_feature (const struct protocol_feature *feature,
3777 enum packet_support support,
3780 struct remote_state *rs = get_remote_state ();
3782 rs->enable_disable_tracepoints = (support == PACKET_ENABLE);
3786 remote_string_tracing_feature (const struct protocol_feature *feature,
3787 enum packet_support support,
3790 struct remote_state *rs = get_remote_state ();
3792 rs->string_tracing = (support == PACKET_ENABLE);
3795 static struct protocol_feature remote_protocol_features[] = {
3796 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3797 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3798 PACKET_qXfer_auxv },
3799 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3800 PACKET_qXfer_features },
3801 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3802 PACKET_qXfer_libraries },
3803 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3804 PACKET_qXfer_libraries_svr4 },
3805 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
3806 PACKET_qXfer_memory_map },
3807 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3808 PACKET_qXfer_spu_read },
3809 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3810 PACKET_qXfer_spu_write },
3811 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3812 PACKET_qXfer_osdata },
3813 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3814 PACKET_qXfer_threads },
3815 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3816 PACKET_qXfer_traceframe_info },
3817 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3818 PACKET_QPassSignals },
3819 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3820 PACKET_QStartNoAckMode },
3821 { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
3822 { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
3823 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3824 PACKET_qXfer_siginfo_read },
3825 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
3826 PACKET_qXfer_siginfo_write },
3827 { "ConditionalTracepoints", PACKET_DISABLE, remote_cond_tracepoint_feature,
3828 PACKET_ConditionalTracepoints },
3829 { "ConditionalBreakpoints", PACKET_DISABLE, remote_cond_breakpoint_feature,
3830 PACKET_ConditionalBreakpoints },
3831 { "FastTracepoints", PACKET_DISABLE, remote_fast_tracepoint_feature,
3832 PACKET_FastTracepoints },
3833 { "StaticTracepoints", PACKET_DISABLE, remote_static_tracepoint_feature,
3834 PACKET_StaticTracepoints },
3835 {"InstallInTrace", PACKET_DISABLE, remote_install_in_trace_feature,
3836 PACKET_InstallInTrace},
3837 { "DisconnectedTracing", PACKET_DISABLE, remote_disconnected_tracing_feature,
3839 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
3841 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
3843 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
3844 PACKET_TracepointSource },
3845 { "QAllow", PACKET_DISABLE, remote_supported_packet,
3847 { "EnableDisableTracepoints", PACKET_DISABLE,
3848 remote_enable_disable_tracepoint_feature, -1 },
3849 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
3850 PACKET_qXfer_fdpic },
3851 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
3852 PACKET_QDisableRandomization },
3853 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
3854 { "tracenz", PACKET_DISABLE,
3855 remote_string_tracing_feature, -1 },
3858 static char *remote_support_xml;
3860 /* Register string appended to "xmlRegisters=" in qSupported query. */
3863 register_remote_support_xml (const char *xml)
3865 #if defined(HAVE_LIBEXPAT)
3866 if (remote_support_xml == NULL)
3867 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
3870 char *copy = xstrdup (remote_support_xml + 13);
3871 char *p = strtok (copy, ",");
3875 if (strcmp (p, xml) == 0)
3882 while ((p = strtok (NULL, ",")) != NULL);
3885 remote_support_xml = reconcat (remote_support_xml,
3886 remote_support_xml, ",", xml,
3893 remote_query_supported_append (char *msg, const char *append)
3896 return reconcat (msg, msg, ";", append, (char *) NULL);
3898 return xstrdup (append);
3902 remote_query_supported (void)
3904 struct remote_state *rs = get_remote_state ();
3907 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
3909 /* The packet support flags are handled differently for this packet
3910 than for most others. We treat an error, a disabled packet, and
3911 an empty response identically: any features which must be reported
3912 to be used will be automatically disabled. An empty buffer
3913 accomplishes this, since that is also the representation for a list
3914 containing no features. */
3917 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
3920 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
3922 q = remote_query_supported_append (q, "multiprocess+");
3924 if (remote_support_xml)
3925 q = remote_query_supported_append (q, remote_support_xml);
3927 q = remote_query_supported_append (q, "qRelocInsn+");
3929 q = reconcat (q, "qSupported:", q, (char *) NULL);
3932 do_cleanups (old_chain);
3934 getpkt (&rs->buf, &rs->buf_size, 0);
3936 /* If an error occured, warn, but do not return - just reset the
3937 buffer to empty and go on to disable features. */
3938 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
3941 warning (_("Remote failure reply: %s"), rs->buf);
3946 memset (seen, 0, sizeof (seen));
3951 enum packet_support is_supported;
3952 char *p, *end, *name_end, *value;
3954 /* First separate out this item from the rest of the packet. If
3955 there's another item after this, we overwrite the separator
3956 (terminated strings are much easier to work with). */
3958 end = strchr (p, ';');
3961 end = p + strlen (p);
3971 warning (_("empty item in \"qSupported\" response"));
3976 name_end = strchr (p, '=');
3979 /* This is a name=value entry. */
3980 is_supported = PACKET_ENABLE;
3981 value = name_end + 1;
3990 is_supported = PACKET_ENABLE;
3994 is_supported = PACKET_DISABLE;
3998 is_supported = PACKET_SUPPORT_UNKNOWN;
4002 warning (_("unrecognized item \"%s\" "
4003 "in \"qSupported\" response"), p);
4009 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4010 if (strcmp (remote_protocol_features[i].name, p) == 0)
4012 const struct protocol_feature *feature;
4015 feature = &remote_protocol_features[i];
4016 feature->func (feature, is_supported, value);
4021 /* If we increased the packet size, make sure to increase the global
4022 buffer size also. We delay this until after parsing the entire
4023 qSupported packet, because this is the same buffer we were
4025 if (rs->buf_size < rs->explicit_packet_size)
4027 rs->buf_size = rs->explicit_packet_size;
4028 rs->buf = xrealloc (rs->buf, rs->buf_size);
4031 /* Handle the defaults for unmentioned features. */
4032 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4035 const struct protocol_feature *feature;
4037 feature = &remote_protocol_features[i];
4038 feature->func (feature, feature->default_support, NULL);
4044 remote_open_1 (char *name, int from_tty,
4045 struct target_ops *target, int extended_p)
4047 struct remote_state *rs = get_remote_state ();
4050 error (_("To open a remote debug connection, you need to specify what\n"
4051 "serial device is attached to the remote system\n"
4052 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4054 /* See FIXME above. */
4055 if (!target_async_permitted)
4056 wait_forever_enabled_p = 1;
4058 /* If we're connected to a running target, target_preopen will kill it.
4059 But if we're connected to a target system with no running process,
4060 then we will still be connected when it returns. Ask this question
4061 first, before target_preopen has a chance to kill anything. */
4062 if (remote_desc != NULL && !have_inferiors ())
4065 || query (_("Already connected to a remote target. Disconnect? ")))
4068 error (_("Still connected."));
4071 target_preopen (from_tty);
4073 unpush_target (target);
4075 /* This time without a query. If we were connected to an
4076 extended-remote target and target_preopen killed the running
4077 process, we may still be connected. If we are starting "target
4078 remote" now, the extended-remote target will not have been
4079 removed by unpush_target. */
4080 if (remote_desc != NULL && !have_inferiors ())
4083 /* Make sure we send the passed signals list the next time we resume. */
4084 xfree (last_pass_packet);
4085 last_pass_packet = NULL;
4087 remote_fileio_reset ();
4088 reopen_exec_file ();
4091 remote_desc = remote_serial_open (name);
4093 perror_with_name (name);
4095 if (baud_rate != -1)
4097 if (serial_setbaudrate (remote_desc, baud_rate))
4099 /* The requested speed could not be set. Error out to
4100 top level after closing remote_desc. Take care to
4101 set remote_desc to NULL to avoid closing remote_desc
4103 serial_close (remote_desc);
4105 perror_with_name (name);
4109 serial_raw (remote_desc);
4111 /* If there is something sitting in the buffer we might take it as a
4112 response to a command, which would be bad. */
4113 serial_flush_input (remote_desc);
4117 puts_filtered ("Remote debugging using ");
4118 puts_filtered (name);
4119 puts_filtered ("\n");
4121 push_target (target); /* Switch to using remote target now. */
4123 /* Register extra event sources in the event loop. */
4124 remote_async_inferior_event_token
4125 = create_async_event_handler (remote_async_inferior_event_handler,
4127 remote_async_get_pending_events_token
4128 = create_async_event_handler (remote_async_get_pending_events_handler,
4131 /* Reset the target state; these things will be queried either by
4132 remote_query_supported or as they are needed. */
4133 init_all_packet_configs ();
4134 rs->cached_wait_status = 0;
4135 rs->explicit_packet_size = 0;
4137 rs->multi_process_aware = 0;
4138 rs->extended = extended_p;
4139 rs->non_stop_aware = 0;
4140 rs->waiting_for_stop_reply = 0;
4141 rs->ctrlc_pending_p = 0;
4143 general_thread = not_sent_ptid;
4144 continue_thread = not_sent_ptid;
4145 remote_traceframe_number = -1;
4147 /* Probe for ability to use "ThreadInfo" query, as required. */
4148 use_threadinfo_query = 1;
4149 use_threadextra_query = 1;
4151 if (target_async_permitted)
4153 /* With this target we start out by owning the terminal. */
4154 remote_async_terminal_ours_p = 1;
4156 /* FIXME: cagney/1999-09-23: During the initial connection it is
4157 assumed that the target is already ready and able to respond to
4158 requests. Unfortunately remote_start_remote() eventually calls
4159 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
4160 around this. Eventually a mechanism that allows
4161 wait_for_inferior() to expect/get timeouts will be
4163 wait_forever_enabled_p = 0;
4166 /* First delete any symbols previously loaded from shared libraries. */
4167 no_shared_libraries (NULL, 0);
4170 init_thread_list ();
4172 /* Start the remote connection. If error() or QUIT, discard this
4173 target (we'd otherwise be in an inconsistent state) and then
4174 propogate the error on up the exception chain. This ensures that
4175 the caller doesn't stumble along blindly assuming that the
4176 function succeeded. The CLI doesn't have this problem but other
4177 UI's, such as MI do.
4179 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4180 this function should return an error indication letting the
4181 caller restore the previous state. Unfortunately the command
4182 ``target remote'' is directly wired to this function making that
4183 impossible. On a positive note, the CLI side of this problem has
4184 been fixed - the function set_cmd_context() makes it possible for
4185 all the ``target ....'' commands to share a common callback
4186 function. See cli-dump.c. */
4188 volatile struct gdb_exception ex;
4190 TRY_CATCH (ex, RETURN_MASK_ALL)
4192 remote_start_remote (from_tty, target, extended_p);
4196 /* Pop the partially set up target - unless something else did
4197 already before throwing the exception. */
4198 if (remote_desc != NULL)
4200 if (target_async_permitted)
4201 wait_forever_enabled_p = 1;
4202 throw_exception (ex);
4206 if (target_async_permitted)
4207 wait_forever_enabled_p = 1;
4210 /* This takes a program previously attached to and detaches it. After
4211 this is done, GDB can be used to debug some other program. We
4212 better not have left any breakpoints in the target program or it'll
4213 die when it hits one. */
4216 remote_detach_1 (char *args, int from_tty, int extended)
4218 int pid = ptid_get_pid (inferior_ptid);
4219 struct remote_state *rs = get_remote_state ();
4222 error (_("Argument given to \"detach\" when remotely debugging."));
4224 if (!target_has_execution)
4225 error (_("No process to detach from."));
4229 char *exec_file = get_exec_file (0);
4230 if (exec_file == NULL)
4232 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4233 target_pid_to_str (pid_to_ptid (pid)));
4234 gdb_flush (gdb_stdout);
4237 /* Tell the remote target to detach. */
4238 if (remote_multi_process_p (rs))
4239 sprintf (rs->buf, "D;%x", pid);
4241 strcpy (rs->buf, "D");
4244 getpkt (&rs->buf, &rs->buf_size, 0);
4246 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4248 else if (rs->buf[0] == '\0')
4249 error (_("Remote doesn't know how to detach"));
4251 error (_("Can't detach process."));
4253 if (from_tty && !extended)
4254 puts_filtered (_("Ending remote debugging.\n"));
4256 discard_pending_stop_replies (pid);
4257 target_mourn_inferior ();
4261 remote_detach (struct target_ops *ops, char *args, int from_tty)
4263 remote_detach_1 (args, from_tty, 0);
4267 extended_remote_detach (struct target_ops *ops, char *args, int from_tty)
4269 remote_detach_1 (args, from_tty, 1);
4272 /* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4275 remote_disconnect (struct target_ops *target, char *args, int from_tty)
4278 error (_("Argument given to \"disconnect\" when remotely debugging."));
4280 /* Make sure we unpush even the extended remote targets; mourn
4281 won't do it. So call remote_mourn_1 directly instead of
4282 target_mourn_inferior. */
4283 remote_mourn_1 (target);
4286 puts_filtered ("Ending remote debugging.\n");
4289 /* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4290 be chatty about it. */
4293 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
4295 struct remote_state *rs = get_remote_state ();
4297 char *wait_status = NULL;
4299 pid = parse_pid_to_attach (args);
4301 /* Remote PID can be freely equal to getpid, do not check it here the same
4302 way as in other targets. */
4304 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4305 error (_("This target does not support attaching to a process"));
4309 char *exec_file = get_exec_file (0);
4312 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4313 target_pid_to_str (pid_to_ptid (pid)));
4315 printf_unfiltered (_("Attaching to %s\n"),
4316 target_pid_to_str (pid_to_ptid (pid)));
4318 gdb_flush (gdb_stdout);
4321 sprintf (rs->buf, "vAttach;%x", pid);
4323 getpkt (&rs->buf, &rs->buf_size, 0);
4325 if (packet_ok (rs->buf,
4326 &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
4330 /* Save the reply for later. */
4331 wait_status = alloca (strlen (rs->buf) + 1);
4332 strcpy (wait_status, rs->buf);
4334 else if (strcmp (rs->buf, "OK") != 0)
4335 error (_("Attaching to %s failed with: %s"),
4336 target_pid_to_str (pid_to_ptid (pid)),
4339 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4340 error (_("This target does not support attaching to a process"));
4342 error (_("Attaching to %s failed"),
4343 target_pid_to_str (pid_to_ptid (pid)));
4345 set_current_inferior (remote_add_inferior (0, pid, 1));
4347 inferior_ptid = pid_to_ptid (pid);
4351 struct thread_info *thread;
4353 /* Get list of threads. */
4354 remote_threads_info (target);
4356 thread = first_thread_of_process (pid);
4358 inferior_ptid = thread->ptid;
4360 inferior_ptid = pid_to_ptid (pid);
4362 /* Invalidate our notion of the remote current thread. */
4363 record_currthread (minus_one_ptid);
4367 /* Now, if we have thread information, update inferior_ptid. */
4368 inferior_ptid = remote_current_thread (inferior_ptid);
4370 /* Add the main thread to the thread list. */
4371 add_thread_silent (inferior_ptid);
4374 /* Next, if the target can specify a description, read it. We do
4375 this before anything involving memory or registers. */
4376 target_find_description ();
4380 /* Use the previously fetched status. */
4381 gdb_assert (wait_status != NULL);
4383 if (target_can_async_p ())
4385 struct stop_reply *stop_reply;
4386 struct cleanup *old_chain;
4388 stop_reply = stop_reply_xmalloc ();
4389 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
4390 remote_parse_stop_reply (wait_status, stop_reply);
4391 discard_cleanups (old_chain);
4392 push_stop_reply (stop_reply);
4394 target_async (inferior_event_handler, 0);
4398 gdb_assert (wait_status != NULL);
4399 strcpy (rs->buf, wait_status);
4400 rs->cached_wait_status = 1;
4404 gdb_assert (wait_status == NULL);
4408 extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
4410 extended_remote_attach_1 (ops, args, from_tty);
4413 /* Convert hex digit A to a number. */
4418 if (a >= '0' && a <= '9')
4420 else if (a >= 'a' && a <= 'f')
4421 return a - 'a' + 10;
4422 else if (a >= 'A' && a <= 'F')
4423 return a - 'A' + 10;
4425 error (_("Reply contains invalid hex digit %d"), a);
4429 hex2bin (const char *hex, gdb_byte *bin, int count)
4433 for (i = 0; i < count; i++)
4435 if (hex[0] == 0 || hex[1] == 0)
4437 /* Hex string is short, or of uneven length.
4438 Return the count that has been converted so far. */
4441 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
4447 /* Convert number NIB to a hex digit. */
4455 return 'a' + nib - 10;
4459 bin2hex (const gdb_byte *bin, char *hex, int count)
4463 /* May use a length, or a nul-terminated string as input. */
4465 count = strlen ((char *) bin);
4467 for (i = 0; i < count; i++)
4469 *hex++ = tohex ((*bin >> 4) & 0xf);
4470 *hex++ = tohex (*bin++ & 0xf);
4476 /* Check for the availability of vCont. This function should also check
4480 remote_vcont_probe (struct remote_state *rs)
4484 strcpy (rs->buf, "vCont?");
4486 getpkt (&rs->buf, &rs->buf_size, 0);
4489 /* Make sure that the features we assume are supported. */
4490 if (strncmp (buf, "vCont", 5) == 0)
4493 int support_s, support_S, support_c, support_C;
4499 rs->support_vCont_t = 0;
4500 while (p && *p == ';')
4503 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4505 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4507 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4509 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4511 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4512 rs->support_vCont_t = 1;
4514 p = strchr (p, ';');
4517 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4518 BUF will make packet_ok disable the packet. */
4519 if (!support_s || !support_S || !support_c || !support_C)
4523 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4526 /* Helper function for building "vCont" resumptions. Write a
4527 resumption to P. ENDP points to one-passed-the-end of the buffer
4528 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4529 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4530 resumed thread should be single-stepped and/or signalled. If PTID
4531 equals minus_one_ptid, then all threads are resumed; if PTID
4532 represents a process, then all threads of the process are resumed;
4533 the thread to be stepped and/or signalled is given in the global
4537 append_resumption (char *p, char *endp,
4538 ptid_t ptid, int step, enum target_signal siggnal)
4540 struct remote_state *rs = get_remote_state ();
4542 if (step && siggnal != TARGET_SIGNAL_0)
4543 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4545 p += xsnprintf (p, endp - p, ";s");
4546 else if (siggnal != TARGET_SIGNAL_0)
4547 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4549 p += xsnprintf (p, endp - p, ";c");
4551 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4555 /* All (-1) threads of process. */
4556 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4558 p += xsnprintf (p, endp - p, ":");
4559 p = write_ptid (p, endp, nptid);
4561 else if (!ptid_equal (ptid, minus_one_ptid))
4563 p += xsnprintf (p, endp - p, ":");
4564 p = write_ptid (p, endp, ptid);
4570 /* Resume the remote inferior by using a "vCont" packet. The thread
4571 to be resumed is PTID; STEP and SIGGNAL indicate whether the
4572 resumed thread should be single-stepped and/or signalled. If PTID
4573 equals minus_one_ptid, then all threads are resumed; the thread to
4574 be stepped and/or signalled is given in the global INFERIOR_PTID.
4575 This function returns non-zero iff it resumes the inferior.
4577 This function issues a strict subset of all possible vCont commands at the
4581 remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
4583 struct remote_state *rs = get_remote_state ();
4587 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
4588 remote_vcont_probe (rs);
4590 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
4594 endp = rs->buf + get_remote_packet_size ();
4596 /* If we could generate a wider range of packets, we'd have to worry
4597 about overflowing BUF. Should there be a generic
4598 "multi-part-packet" packet? */
4600 p += xsnprintf (p, endp - p, "vCont");
4602 if (ptid_equal (ptid, magic_null_ptid))
4604 /* MAGIC_NULL_PTID means that we don't have any active threads,
4605 so we don't have any TID numbers the inferior will
4606 understand. Make sure to only send forms that do not specify
4608 append_resumption (p, endp, minus_one_ptid, step, siggnal);
4610 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4612 /* Resume all threads (of all processes, or of a single
4613 process), with preference for INFERIOR_PTID. This assumes
4614 inferior_ptid belongs to the set of all threads we are about
4616 if (step || siggnal != TARGET_SIGNAL_0)
4618 /* Step inferior_ptid, with or without signal. */
4619 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
4622 /* And continue others without a signal. */
4623 append_resumption (p, endp, ptid, /*step=*/ 0, TARGET_SIGNAL_0);
4627 /* Scheduler locking; resume only PTID. */
4628 append_resumption (p, endp, ptid, step, siggnal);
4631 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4636 /* In non-stop, the stub replies to vCont with "OK". The stop
4637 reply will be reported asynchronously by means of a `%Stop'
4639 getpkt (&rs->buf, &rs->buf_size, 0);
4640 if (strcmp (rs->buf, "OK") != 0)
4641 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4647 /* Tell the remote machine to resume. */
4649 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
4651 static int last_sent_step;
4654 remote_resume (struct target_ops *ops,
4655 ptid_t ptid, int step, enum target_signal siggnal)
4657 struct remote_state *rs = get_remote_state ();
4660 last_sent_signal = siggnal;
4661 last_sent_step = step;
4663 /* The vCont packet doesn't need to specify threads via Hc. */
4664 /* No reverse support (yet) for vCont. */
4665 if (execution_direction != EXEC_REVERSE)
4666 if (remote_vcont_resume (ptid, step, siggnal))
4669 /* All other supported resume packets do use Hc, so set the continue
4671 if (ptid_equal (ptid, minus_one_ptid))
4672 set_continue_thread (any_thread_ptid);
4674 set_continue_thread (ptid);
4677 if (execution_direction == EXEC_REVERSE)
4679 /* We don't pass signals to the target in reverse exec mode. */
4680 if (info_verbose && siggnal != TARGET_SIGNAL_0)
4681 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
4685 && remote_protocol_packets[PACKET_bs].support == PACKET_DISABLE)
4686 error (_("Remote reverse-step not supported."));
4688 && remote_protocol_packets[PACKET_bc].support == PACKET_DISABLE)
4689 error (_("Remote reverse-continue not supported."));
4691 strcpy (buf, step ? "bs" : "bc");
4693 else if (siggnal != TARGET_SIGNAL_0)
4695 buf[0] = step ? 'S' : 'C';
4696 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
4697 buf[2] = tohex (((int) siggnal) & 0xf);
4701 strcpy (buf, step ? "s" : "c");
4706 /* We are about to start executing the inferior, let's register it
4707 with the event loop. NOTE: this is the one place where all the
4708 execution commands end up. We could alternatively do this in each
4709 of the execution commands in infcmd.c. */
4710 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4711 into infcmd.c in order to allow inferior function calls to work
4712 NOT asynchronously. */
4713 if (target_can_async_p ())
4714 target_async (inferior_event_handler, 0);
4716 /* We've just told the target to resume. The remote server will
4717 wait for the inferior to stop, and then send a stop reply. In
4718 the mean time, we can't start another command/query ourselves
4719 because the stub wouldn't be ready to process it. This applies
4720 only to the base all-stop protocol, however. In non-stop (which
4721 only supports vCont), the stub replies with an "OK", and is
4722 immediate able to process further serial input. */
4724 rs->waiting_for_stop_reply = 1;
4728 /* Set up the signal handler for SIGINT, while the target is
4729 executing, ovewriting the 'regular' SIGINT signal handler. */
4731 initialize_sigint_signal_handler (void)
4733 signal (SIGINT, handle_remote_sigint);
4736 /* Signal handler for SIGINT, while the target is executing. */
4738 handle_remote_sigint (int sig)
4740 signal (sig, handle_remote_sigint_twice);
4741 mark_async_signal_handler_wrapper (sigint_remote_token);
4744 /* Signal handler for SIGINT, installed after SIGINT has already been
4745 sent once. It will take effect the second time that the user sends
4748 handle_remote_sigint_twice (int sig)
4750 signal (sig, handle_remote_sigint);
4751 mark_async_signal_handler_wrapper (sigint_remote_twice_token);
4754 /* Perform the real interruption of the target execution, in response
4757 async_remote_interrupt (gdb_client_data arg)
4760 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
4762 target_stop (inferior_ptid);
4765 /* Perform interrupt, if the first attempt did not succeed. Just give
4766 up on the target alltogether. */
4768 async_remote_interrupt_twice (gdb_client_data arg)
4771 fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
4776 /* Reinstall the usual SIGINT handlers, after the target has
4779 cleanup_sigint_signal_handler (void *dummy)
4781 signal (SIGINT, handle_sigint);
4784 /* Send ^C to target to halt it. Target will respond, and send us a
4786 static void (*ofunc) (int);
4788 /* The command line interface's stop routine. This function is installed
4789 as a signal handler for SIGINT. The first time a user requests a
4790 stop, we call remote_stop to send a break or ^C. If there is no
4791 response from the target (it didn't stop when the user requested it),
4792 we ask the user if he'd like to detach from the target. */
4794 remote_interrupt (int signo)
4796 /* If this doesn't work, try more severe steps. */
4797 signal (signo, remote_interrupt_twice);
4799 gdb_call_async_signal_handler (sigint_remote_token, 1);
4802 /* The user typed ^C twice. */
4805 remote_interrupt_twice (int signo)
4807 signal (signo, ofunc);
4808 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
4809 signal (signo, remote_interrupt);
4812 /* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
4813 thread, all threads of a remote process, or all threads of all
4817 remote_stop_ns (ptid_t ptid)
4819 struct remote_state *rs = get_remote_state ();
4821 char *endp = rs->buf + get_remote_packet_size ();
4823 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
4824 remote_vcont_probe (rs);
4826 if (!rs->support_vCont_t)
4827 error (_("Remote server does not support stopping threads"));
4829 if (ptid_equal (ptid, minus_one_ptid)
4830 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4831 p += xsnprintf (p, endp - p, "vCont;t");
4836 p += xsnprintf (p, endp - p, "vCont;t:");
4838 if (ptid_is_pid (ptid))
4839 /* All (-1) threads of process. */
4840 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4843 /* Small optimization: if we already have a stop reply for
4844 this thread, no use in telling the stub we want this
4846 if (peek_stop_reply (ptid))
4852 write_ptid (p, endp, nptid);
4855 /* In non-stop, we get an immediate OK reply. The stop reply will
4856 come in asynchronously by notification. */
4858 getpkt (&rs->buf, &rs->buf_size, 0);
4859 if (strcmp (rs->buf, "OK") != 0)
4860 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
4863 /* All-stop version of target_stop. Sends a break or a ^C to stop the
4864 remote target. It is undefined which thread of which process
4865 reports the stop. */
4868 remote_stop_as (ptid_t ptid)
4870 struct remote_state *rs = get_remote_state ();
4872 rs->ctrlc_pending_p = 1;
4874 /* If the inferior is stopped already, but the core didn't know
4875 about it yet, just ignore the request. The cached wait status
4876 will be collected in remote_wait. */
4877 if (rs->cached_wait_status)
4880 /* Send interrupt_sequence to remote target. */
4881 send_interrupt_sequence ();
4884 /* This is the generic stop called via the target vector. When a target
4885 interrupt is requested, either by the command line or the GUI, we
4886 will eventually end up here. */
4889 remote_stop (ptid_t ptid)
4892 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
4895 remote_stop_ns (ptid);
4897 remote_stop_as (ptid);
4900 /* Ask the user what to do when an interrupt is received. */
4903 interrupt_query (void)
4905 target_terminal_ours ();
4907 if (target_can_async_p ())
4909 signal (SIGINT, handle_sigint);
4910 deprecated_throw_reason (RETURN_QUIT);
4914 if (query (_("Interrupted while waiting for the program.\n\
4915 Give up (and stop debugging it)? ")))
4918 deprecated_throw_reason (RETURN_QUIT);
4922 target_terminal_inferior ();
4925 /* Enable/disable target terminal ownership. Most targets can use
4926 terminal groups to control terminal ownership. Remote targets are
4927 different in that explicit transfer of ownership to/from GDB/target
4931 remote_terminal_inferior (void)
4933 if (!target_async_permitted)
4934 /* Nothing to do. */
4937 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
4938 idempotent. The event-loop GDB talking to an asynchronous target
4939 with a synchronous command calls this function from both
4940 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
4941 transfer the terminal to the target when it shouldn't this guard
4943 if (!remote_async_terminal_ours_p)
4945 delete_file_handler (input_fd);
4946 remote_async_terminal_ours_p = 0;
4947 initialize_sigint_signal_handler ();
4948 /* NOTE: At this point we could also register our selves as the
4949 recipient of all input. Any characters typed could then be
4950 passed on down to the target. */
4954 remote_terminal_ours (void)
4956 if (!target_async_permitted)
4957 /* Nothing to do. */
4960 /* See FIXME in remote_terminal_inferior. */
4961 if (remote_async_terminal_ours_p)
4963 cleanup_sigint_signal_handler (NULL);
4964 add_file_handler (input_fd, stdin_event_handler, 0);
4965 remote_async_terminal_ours_p = 1;
4969 remote_console_output (char *msg)
4973 for (p = msg; p[0] && p[1]; p += 2)
4976 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
4980 fputs_unfiltered (tb, gdb_stdtarg);
4982 gdb_flush (gdb_stdtarg);
4985 typedef struct cached_reg
4988 gdb_byte data[MAX_REGISTER_SIZE];
4991 DEF_VEC_O(cached_reg_t);
4995 struct stop_reply *next;
4999 struct target_waitstatus ws;
5001 /* Expedited registers. This makes remote debugging a bit more
5002 efficient for those targets that provide critical registers as
5003 part of their normal status mechanism (as another roundtrip to
5004 fetch them is avoided). */
5005 VEC(cached_reg_t) *regcache;
5007 int stopped_by_watchpoint_p;
5008 CORE_ADDR watch_data_address;
5016 /* The list of already fetched and acknowledged stop events. */
5017 static struct stop_reply *stop_reply_queue;
5019 static struct stop_reply *
5020 stop_reply_xmalloc (void)
5022 struct stop_reply *r = XMALLOC (struct stop_reply);
5029 stop_reply_xfree (struct stop_reply *r)
5033 VEC_free (cached_reg_t, r->regcache);
5038 /* Discard all pending stop replies of inferior PID. If PID is -1,
5039 discard everything. */
5042 discard_pending_stop_replies (int pid)
5044 struct stop_reply *prev = NULL, *reply, *next;
5046 /* Discard the in-flight notification. */
5047 if (pending_stop_reply != NULL
5049 || ptid_get_pid (pending_stop_reply->ptid) == pid))
5051 stop_reply_xfree (pending_stop_reply);
5052 pending_stop_reply = NULL;
5055 /* Discard the stop replies we have already pulled with
5057 for (reply = stop_reply_queue; reply; reply = next)
5061 || ptid_get_pid (reply->ptid) == pid)
5063 if (reply == stop_reply_queue)
5064 stop_reply_queue = reply->next;
5066 prev->next = reply->next;
5068 stop_reply_xfree (reply);
5075 /* Cleanup wrapper. */
5078 do_stop_reply_xfree (void *arg)
5080 struct stop_reply *r = arg;
5082 stop_reply_xfree (r);
5085 /* Look for a queued stop reply belonging to PTID. If one is found,
5086 remove it from the queue, and return it. Returns NULL if none is
5087 found. If there are still queued events left to process, tell the
5088 event loop to get back to target_wait soon. */
5090 static struct stop_reply *
5091 queued_stop_reply (ptid_t ptid)
5093 struct stop_reply *it;
5094 struct stop_reply **it_link;
5096 it = stop_reply_queue;
5097 it_link = &stop_reply_queue;
5100 if (ptid_match (it->ptid, ptid))
5102 *it_link = it->next;
5107 it_link = &it->next;
5111 if (stop_reply_queue)
5112 /* There's still at least an event left. */
5113 mark_async_event_handler (remote_async_inferior_event_token);
5118 /* Push a fully parsed stop reply in the stop reply queue. Since we
5119 know that we now have at least one queued event left to pass to the
5120 core side, tell the event loop to get back to target_wait soon. */
5123 push_stop_reply (struct stop_reply *new_event)
5125 struct stop_reply *event;
5127 if (stop_reply_queue)
5129 for (event = stop_reply_queue;
5130 event && event->next;
5131 event = event->next)
5134 event->next = new_event;
5137 stop_reply_queue = new_event;
5139 mark_async_event_handler (remote_async_inferior_event_token);
5142 /* Returns true if we have a stop reply for PTID. */
5145 peek_stop_reply (ptid_t ptid)
5147 struct stop_reply *it;
5149 for (it = stop_reply_queue; it; it = it->next)
5150 if (ptid_equal (ptid, it->ptid))
5152 if (it->ws.kind == TARGET_WAITKIND_STOPPED)
5159 /* Parse the stop reply in BUF. Either the function succeeds, and the
5160 result is stored in EVENT, or throws an error. */
5163 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5165 struct remote_arch_state *rsa = get_remote_arch_state ();
5169 event->ptid = null_ptid;
5170 event->ws.kind = TARGET_WAITKIND_IGNORE;
5171 event->ws.value.integer = 0;
5172 event->solibs_changed = 0;
5173 event->replay_event = 0;
5174 event->stopped_by_watchpoint_p = 0;
5175 event->regcache = NULL;
5180 case 'T': /* Status with PC, SP, FP, ... */
5181 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5182 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5184 n... = register number
5185 r... = register contents
5188 p = &buf[3]; /* after Txx */
5196 /* If the packet contains a register number, save it in
5197 pnum and set p1 to point to the character following it.
5198 Otherwise p1 points to p. */
5200 /* If this packet is an awatch packet, don't parse the 'a'
5201 as a register number. */
5203 if (strncmp (p, "awatch", strlen("awatch")) != 0
5204 && strncmp (p, "core", strlen ("core") != 0))
5206 /* Read the ``P'' register number. */
5207 pnum = strtol (p, &p_temp, 16);
5213 if (p1 == p) /* No register number present here. */
5215 p1 = strchr (p, ':');
5217 error (_("Malformed packet(a) (missing colon): %s\n\
5220 if (strncmp (p, "thread", p1 - p) == 0)
5221 event->ptid = read_ptid (++p1, &p);
5222 else if ((strncmp (p, "watch", p1 - p) == 0)
5223 || (strncmp (p, "rwatch", p1 - p) == 0)
5224 || (strncmp (p, "awatch", p1 - p) == 0))
5226 event->stopped_by_watchpoint_p = 1;
5227 p = unpack_varlen_hex (++p1, &addr);
5228 event->watch_data_address = (CORE_ADDR) addr;
5230 else if (strncmp (p, "library", p1 - p) == 0)
5234 while (*p_temp && *p_temp != ';')
5237 event->solibs_changed = 1;
5240 else if (strncmp (p, "replaylog", p1 - p) == 0)
5242 /* NO_HISTORY event.
5243 p1 will indicate "begin" or "end", but
5244 it makes no difference for now, so ignore it. */
5245 event->replay_event = 1;
5246 p_temp = strchr (p1 + 1, ';');
5250 else if (strncmp (p, "core", p1 - p) == 0)
5254 p = unpack_varlen_hex (++p1, &c);
5259 /* Silently skip unknown optional info. */
5260 p_temp = strchr (p1 + 1, ';');
5267 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5268 cached_reg_t cached_reg;
5273 error (_("Malformed packet(b) (missing colon): %s\n\
5279 error (_("Remote sent bad register number %s: %s\n\
5281 hex_string (pnum), p, buf);
5283 cached_reg.num = reg->regnum;
5285 fieldsize = hex2bin (p, cached_reg.data,
5286 register_size (target_gdbarch,
5289 if (fieldsize < register_size (target_gdbarch,
5291 warning (_("Remote reply is too short: %s"), buf);
5293 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5297 error (_("Remote register badly formatted: %s\nhere: %s"),
5302 case 'S': /* Old style status, just signal only. */
5303 if (event->solibs_changed)
5304 event->ws.kind = TARGET_WAITKIND_LOADED;
5305 else if (event->replay_event)
5306 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5309 event->ws.kind = TARGET_WAITKIND_STOPPED;
5310 event->ws.value.sig = (enum target_signal)
5311 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
5314 case 'W': /* Target exited. */
5321 /* GDB used to accept only 2 hex chars here. Stubs should
5322 only send more if they detect GDB supports multi-process
5324 p = unpack_varlen_hex (&buf[1], &value);
5328 /* The remote process exited. */
5329 event->ws.kind = TARGET_WAITKIND_EXITED;
5330 event->ws.value.integer = value;
5334 /* The remote process exited with a signal. */
5335 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5336 event->ws.value.sig = (enum target_signal) value;
5339 /* If no process is specified, assume inferior_ptid. */
5340 pid = ptid_get_pid (inferior_ptid);
5349 else if (strncmp (p,
5350 "process:", sizeof ("process:") - 1) == 0)
5354 p += sizeof ("process:") - 1;
5355 unpack_varlen_hex (p, &upid);
5359 error (_("unknown stop reply packet: %s"), buf);
5362 error (_("unknown stop reply packet: %s"), buf);
5363 event->ptid = pid_to_ptid (pid);
5368 if (non_stop && ptid_equal (event->ptid, null_ptid))
5369 error (_("No process or thread specified in stop reply: %s"), buf);
5372 /* When the stub wants to tell GDB about a new stop reply, it sends a
5373 stop notification (%Stop). Those can come it at any time, hence,
5374 we have to make sure that any pending putpkt/getpkt sequence we're
5375 making is finished, before querying the stub for more events with
5376 vStopped. E.g., if we started a vStopped sequence immediatelly
5377 upon receiving the %Stop notification, something like this could
5385 1.6) <-- (registers reply to step #1.3)
5387 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5390 To solve this, whenever we parse a %Stop notification sucessfully,
5391 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5392 doing whatever we were doing:
5398 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5399 2.5) <-- (registers reply to step #2.3)
5401 Eventualy after step #2.5, we return to the event loop, which
5402 notices there's an event on the
5403 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5404 associated callback --- the function below. At this point, we're
5405 always safe to start a vStopped sequence. :
5408 2.7) <-- T05 thread:2
5414 remote_get_pending_stop_replies (void)
5416 struct remote_state *rs = get_remote_state ();
5418 if (pending_stop_reply)
5421 putpkt ("vStopped");
5423 /* Now we can rely on it. */
5424 push_stop_reply (pending_stop_reply);
5425 pending_stop_reply = NULL;
5429 getpkt (&rs->buf, &rs->buf_size, 0);
5430 if (strcmp (rs->buf, "OK") == 0)
5434 struct cleanup *old_chain;
5435 struct stop_reply *stop_reply = stop_reply_xmalloc ();
5437 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
5438 remote_parse_stop_reply (rs->buf, stop_reply);
5441 putpkt ("vStopped");
5443 if (stop_reply->ws.kind != TARGET_WAITKIND_IGNORE)
5445 /* Now we can rely on it. */
5446 discard_cleanups (old_chain);
5447 push_stop_reply (stop_reply);
5450 /* We got an unknown stop reply. */
5451 do_cleanups (old_chain);
5458 /* Called when it is decided that STOP_REPLY holds the info of the
5459 event that is to be returned to the core. This function always
5460 destroys STOP_REPLY. */
5463 process_stop_reply (struct stop_reply *stop_reply,
5464 struct target_waitstatus *status)
5468 *status = stop_reply->ws;
5469 ptid = stop_reply->ptid;
5471 /* If no thread/process was reported by the stub, assume the current
5473 if (ptid_equal (ptid, null_ptid))
5474 ptid = inferior_ptid;
5476 if (status->kind != TARGET_WAITKIND_EXITED
5477 && status->kind != TARGET_WAITKIND_SIGNALLED)
5479 /* Expedited registers. */
5480 if (stop_reply->regcache)
5482 struct regcache *regcache
5483 = get_thread_arch_regcache (ptid, target_gdbarch);
5488 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5490 regcache_raw_supply (regcache, reg->num, reg->data);
5491 VEC_free (cached_reg_t, stop_reply->regcache);
5494 remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5495 remote_watch_data_address = stop_reply->watch_data_address;
5497 remote_notice_new_inferior (ptid, 0);
5498 demand_private_info (ptid)->core = stop_reply->core;
5501 stop_reply_xfree (stop_reply);
5505 /* The non-stop mode version of target_wait. */
5508 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
5510 struct remote_state *rs = get_remote_state ();
5511 struct stop_reply *stop_reply;
5514 /* If in non-stop mode, get out of getpkt even if a
5515 notification is received. */
5517 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5524 case 'E': /* Error of some sort. */
5525 /* We're out of sync with the target now. Did it continue
5526 or not? We can't tell which thread it was in non-stop,
5527 so just ignore this. */
5528 warning (_("Remote failure reply: %s"), rs->buf);
5530 case 'O': /* Console output. */
5531 remote_console_output (rs->buf + 1);
5534 warning (_("Invalid remote reply: %s"), rs->buf);
5538 /* Acknowledge a pending stop reply that may have arrived in the
5540 if (pending_stop_reply != NULL)
5541 remote_get_pending_stop_replies ();
5543 /* If indeed we noticed a stop reply, we're done. */
5544 stop_reply = queued_stop_reply (ptid);
5545 if (stop_reply != NULL)
5546 return process_stop_reply (stop_reply, status);
5548 /* Still no event. If we're just polling for an event, then
5549 return to the event loop. */
5550 if (options & TARGET_WNOHANG)
5552 status->kind = TARGET_WAITKIND_IGNORE;
5553 return minus_one_ptid;
5556 /* Otherwise do a blocking wait. */
5557 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5562 /* Wait until the remote machine stops, then return, storing status in
5563 STATUS just as `wait' would. */
5566 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
5568 struct remote_state *rs = get_remote_state ();
5569 ptid_t event_ptid = null_ptid;
5571 struct stop_reply *stop_reply;
5575 status->kind = TARGET_WAITKIND_IGNORE;
5576 status->value.integer = 0;
5578 stop_reply = queued_stop_reply (ptid);
5579 if (stop_reply != NULL)
5580 return process_stop_reply (stop_reply, status);
5582 if (rs->cached_wait_status)
5583 /* Use the cached wait status, but only once. */
5584 rs->cached_wait_status = 0;
5589 if (!target_is_async_p ())
5591 ofunc = signal (SIGINT, remote_interrupt);
5592 /* If the user hit C-c before this packet, or between packets,
5593 pretend that it was hit right here. */
5597 remote_interrupt (SIGINT);
5601 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5602 _never_ wait for ever -> test on target_is_async_p().
5603 However, before we do that we need to ensure that the caller
5604 knows how to take the target into/out of async mode. */
5605 ret = getpkt_sane (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
5606 if (!target_is_async_p ())
5607 signal (SIGINT, ofunc);
5612 remote_stopped_by_watchpoint_p = 0;
5614 /* We got something. */
5615 rs->waiting_for_stop_reply = 0;
5617 /* Assume that the target has acknowledged Ctrl-C unless we receive
5618 an 'F' or 'O' packet. */
5619 if (buf[0] != 'F' && buf[0] != 'O')
5620 rs->ctrlc_pending_p = 0;
5624 case 'E': /* Error of some sort. */
5625 /* We're out of sync with the target now. Did it continue or
5626 not? Not is more likely, so report a stop. */
5627 warning (_("Remote failure reply: %s"), buf);
5628 status->kind = TARGET_WAITKIND_STOPPED;
5629 status->value.sig = TARGET_SIGNAL_0;
5631 case 'F': /* File-I/O request. */
5632 remote_fileio_request (buf, rs->ctrlc_pending_p);
5633 rs->ctrlc_pending_p = 0;
5635 case 'T': case 'S': case 'X': case 'W':
5637 struct stop_reply *stop_reply;
5638 struct cleanup *old_chain;
5640 stop_reply = stop_reply_xmalloc ();
5641 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
5642 remote_parse_stop_reply (buf, stop_reply);
5643 discard_cleanups (old_chain);
5644 event_ptid = process_stop_reply (stop_reply, status);
5647 case 'O': /* Console output. */
5648 remote_console_output (buf + 1);
5650 /* The target didn't really stop; keep waiting. */
5651 rs->waiting_for_stop_reply = 1;
5655 if (last_sent_signal != TARGET_SIGNAL_0)
5657 /* Zero length reply means that we tried 'S' or 'C' and the
5658 remote system doesn't support it. */
5659 target_terminal_ours_for_output ();
5661 ("Can't send signals to this remote system. %s not sent.\n",
5662 target_signal_to_name (last_sent_signal));
5663 last_sent_signal = TARGET_SIGNAL_0;
5664 target_terminal_inferior ();
5666 strcpy ((char *) buf, last_sent_step ? "s" : "c");
5667 putpkt ((char *) buf);
5669 /* We just told the target to resume, so a stop reply is in
5671 rs->waiting_for_stop_reply = 1;
5674 /* else fallthrough */
5676 warning (_("Invalid remote reply: %s"), buf);
5678 rs->waiting_for_stop_reply = 1;
5682 if (status->kind == TARGET_WAITKIND_IGNORE)
5684 /* Nothing interesting happened. If we're doing a non-blocking
5685 poll, we're done. Otherwise, go back to waiting. */
5686 if (options & TARGET_WNOHANG)
5687 return minus_one_ptid;
5691 else if (status->kind != TARGET_WAITKIND_EXITED
5692 && status->kind != TARGET_WAITKIND_SIGNALLED)
5694 if (!ptid_equal (event_ptid, null_ptid))
5695 record_currthread (event_ptid);
5697 event_ptid = inferior_ptid;
5700 /* A process exit. Invalidate our notion of current thread. */
5701 record_currthread (minus_one_ptid);
5706 /* Wait until the remote machine stops, then return, storing status in
5707 STATUS just as `wait' would. */
5710 remote_wait (struct target_ops *ops,
5711 ptid_t ptid, struct target_waitstatus *status, int options)
5716 event_ptid = remote_wait_ns (ptid, status, options);
5718 event_ptid = remote_wait_as (ptid, status, options);
5720 if (target_can_async_p ())
5722 /* If there are are events left in the queue tell the event loop
5724 if (stop_reply_queue)
5725 mark_async_event_handler (remote_async_inferior_event_token);
5731 /* Fetch a single register using a 'p' packet. */
5734 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
5736 struct remote_state *rs = get_remote_state ();
5738 char regp[MAX_REGISTER_SIZE];
5741 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
5744 if (reg->pnum == -1)
5749 p += hexnumstr (p, reg->pnum);
5752 getpkt (&rs->buf, &rs->buf_size, 0);
5756 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
5760 case PACKET_UNKNOWN:
5763 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
5764 gdbarch_register_name (get_regcache_arch (regcache),
5769 /* If this register is unfetchable, tell the regcache. */
5772 regcache_raw_supply (regcache, reg->regnum, NULL);
5776 /* Otherwise, parse and supply the value. */
5782 error (_("fetch_register_using_p: early buf termination"));
5784 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
5787 regcache_raw_supply (regcache, reg->regnum, regp);
5791 /* Fetch the registers included in the target's 'g' packet. */
5794 send_g_packet (void)
5796 struct remote_state *rs = get_remote_state ();
5799 sprintf (rs->buf, "g");
5800 remote_send (&rs->buf, &rs->buf_size);
5802 /* We can get out of synch in various cases. If the first character
5803 in the buffer is not a hex character, assume that has happened
5804 and try to fetch another packet to read. */
5805 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
5806 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
5807 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
5808 && rs->buf[0] != 'x') /* New: unavailable register value. */
5811 fprintf_unfiltered (gdb_stdlog,
5812 "Bad register packet; fetching a new packet\n");
5813 getpkt (&rs->buf, &rs->buf_size, 0);
5816 buf_len = strlen (rs->buf);
5818 /* Sanity check the received packet. */
5819 if (buf_len % 2 != 0)
5820 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
5826 process_g_packet (struct regcache *regcache)
5828 struct gdbarch *gdbarch = get_regcache_arch (regcache);
5829 struct remote_state *rs = get_remote_state ();
5830 struct remote_arch_state *rsa = get_remote_arch_state ();
5835 buf_len = strlen (rs->buf);
5837 /* Further sanity checks, with knowledge of the architecture. */
5838 if (buf_len > 2 * rsa->sizeof_g_packet)
5839 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
5841 /* Save the size of the packet sent to us by the target. It is used
5842 as a heuristic when determining the max size of packets that the
5843 target can safely receive. */
5844 if (rsa->actual_register_packet_size == 0)
5845 rsa->actual_register_packet_size = buf_len;
5847 /* If this is smaller than we guessed the 'g' packet would be,
5848 update our records. A 'g' reply that doesn't include a register's
5849 value implies either that the register is not available, or that
5850 the 'p' packet must be used. */
5851 if (buf_len < 2 * rsa->sizeof_g_packet)
5853 rsa->sizeof_g_packet = buf_len / 2;
5855 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
5857 if (rsa->regs[i].pnum == -1)
5860 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
5861 rsa->regs[i].in_g_packet = 0;
5863 rsa->regs[i].in_g_packet = 1;
5867 regs = alloca (rsa->sizeof_g_packet);
5869 /* Unimplemented registers read as all bits zero. */
5870 memset (regs, 0, rsa->sizeof_g_packet);
5872 /* Reply describes registers byte by byte, each byte encoded as two
5873 hex characters. Suck them all up, then supply them to the
5874 register cacheing/storage mechanism. */
5877 for (i = 0; i < rsa->sizeof_g_packet; i++)
5879 if (p[0] == 0 || p[1] == 0)
5880 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
5881 internal_error (__FILE__, __LINE__,
5882 _("unexpected end of 'g' packet reply"));
5884 if (p[0] == 'x' && p[1] == 'x')
5885 regs[i] = 0; /* 'x' */
5887 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
5891 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
5893 struct packet_reg *r = &rsa->regs[i];
5897 if (r->offset * 2 >= strlen (rs->buf))
5898 /* This shouldn't happen - we adjusted in_g_packet above. */
5899 internal_error (__FILE__, __LINE__,
5900 _("unexpected end of 'g' packet reply"));
5901 else if (rs->buf[r->offset * 2] == 'x')
5903 gdb_assert (r->offset * 2 < strlen (rs->buf));
5904 /* The register isn't available, mark it as such (at
5905 the same time setting the value to zero). */
5906 regcache_raw_supply (regcache, r->regnum, NULL);
5909 regcache_raw_supply (regcache, r->regnum,
5916 fetch_registers_using_g (struct regcache *regcache)
5919 process_g_packet (regcache);
5922 /* Make the remote selected traceframe match GDB's selected
5926 set_remote_traceframe (void)
5930 if (remote_traceframe_number == get_traceframe_number ())
5933 /* Avoid recursion, remote_trace_find calls us again. */
5934 remote_traceframe_number = get_traceframe_number ();
5936 newnum = target_trace_find (tfind_number,
5937 get_traceframe_number (), 0, 0, NULL);
5939 /* Should not happen. If it does, all bets are off. */
5940 if (newnum != get_traceframe_number ())
5941 warning (_("could not set remote traceframe"));
5945 remote_fetch_registers (struct target_ops *ops,
5946 struct regcache *regcache, int regnum)
5948 struct remote_arch_state *rsa = get_remote_arch_state ();
5951 set_remote_traceframe ();
5952 set_general_thread (inferior_ptid);
5956 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
5958 gdb_assert (reg != NULL);
5960 /* If this register might be in the 'g' packet, try that first -
5961 we are likely to read more than one register. If this is the
5962 first 'g' packet, we might be overly optimistic about its
5963 contents, so fall back to 'p'. */
5964 if (reg->in_g_packet)
5966 fetch_registers_using_g (regcache);
5967 if (reg->in_g_packet)
5971 if (fetch_register_using_p (regcache, reg))
5974 /* This register is not available. */
5975 regcache_raw_supply (regcache, reg->regnum, NULL);
5980 fetch_registers_using_g (regcache);
5982 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5983 if (!rsa->regs[i].in_g_packet)
5984 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
5986 /* This register is not available. */
5987 regcache_raw_supply (regcache, i, NULL);
5991 /* Prepare to store registers. Since we may send them all (using a
5992 'G' request), we have to read out the ones we don't want to change
5996 remote_prepare_to_store (struct regcache *regcache)
5998 struct remote_arch_state *rsa = get_remote_arch_state ();
6000 gdb_byte buf[MAX_REGISTER_SIZE];
6002 /* Make sure the entire registers array is valid. */
6003 switch (remote_protocol_packets[PACKET_P].support)
6005 case PACKET_DISABLE:
6006 case PACKET_SUPPORT_UNKNOWN:
6007 /* Make sure all the necessary registers are cached. */
6008 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6009 if (rsa->regs[i].in_g_packet)
6010 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6017 /* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
6018 packet was not recognized. */
6021 store_register_using_P (const struct regcache *regcache,
6022 struct packet_reg *reg)
6024 struct gdbarch *gdbarch = get_regcache_arch (regcache);
6025 struct remote_state *rs = get_remote_state ();
6026 /* Try storing a single register. */
6027 char *buf = rs->buf;
6028 gdb_byte regp[MAX_REGISTER_SIZE];
6031 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
6034 if (reg->pnum == -1)
6037 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6038 p = buf + strlen (buf);
6039 regcache_raw_collect (regcache, reg->regnum, regp);
6040 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6042 getpkt (&rs->buf, &rs->buf_size, 0);
6044 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6049 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6050 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6051 case PACKET_UNKNOWN:
6054 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6058 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6059 contents of the register cache buffer. FIXME: ignores errors. */
6062 store_registers_using_G (const struct regcache *regcache)
6064 struct remote_state *rs = get_remote_state ();
6065 struct remote_arch_state *rsa = get_remote_arch_state ();
6069 /* Extract all the registers in the regcache copying them into a
6074 regs = alloca (rsa->sizeof_g_packet);
6075 memset (regs, 0, rsa->sizeof_g_packet);
6076 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6078 struct packet_reg *r = &rsa->regs[i];
6081 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6085 /* Command describes registers byte by byte,
6086 each byte encoded as two hex characters. */
6089 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6091 bin2hex (regs, p, rsa->sizeof_g_packet);
6093 getpkt (&rs->buf, &rs->buf_size, 0);
6094 if (packet_check_result (rs->buf) == PACKET_ERROR)
6095 error (_("Could not write registers; remote failure reply '%s'"),
6099 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6100 of the register cache buffer. FIXME: ignores errors. */
6103 remote_store_registers (struct target_ops *ops,
6104 struct regcache *regcache, int regnum)
6106 struct remote_arch_state *rsa = get_remote_arch_state ();
6109 set_remote_traceframe ();
6110 set_general_thread (inferior_ptid);
6114 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6116 gdb_assert (reg != NULL);
6118 /* Always prefer to store registers using the 'P' packet if
6119 possible; we often change only a small number of registers.
6120 Sometimes we change a larger number; we'd need help from a
6121 higher layer to know to use 'G'. */
6122 if (store_register_using_P (regcache, reg))
6125 /* For now, don't complain if we have no way to write the
6126 register. GDB loses track of unavailable registers too
6127 easily. Some day, this may be an error. We don't have
6128 any way to read the register, either... */
6129 if (!reg->in_g_packet)
6132 store_registers_using_G (regcache);
6136 store_registers_using_G (regcache);
6138 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6139 if (!rsa->regs[i].in_g_packet)
6140 if (!store_register_using_P (regcache, &rsa->regs[i]))
6141 /* See above for why we do not issue an error here. */
6146 /* Return the number of hex digits in num. */
6149 hexnumlen (ULONGEST num)
6153 for (i = 0; num != 0; i++)
6159 /* Set BUF to the minimum number of hex digits representing NUM. */
6162 hexnumstr (char *buf, ULONGEST num)
6164 int len = hexnumlen (num);
6166 return hexnumnstr (buf, num, len);
6170 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
6173 hexnumnstr (char *buf, ULONGEST num, int width)
6179 for (i = width - 1; i >= 0; i--)
6181 buf[i] = "0123456789abcdef"[(num & 0xf)];
6188 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
6191 remote_address_masked (CORE_ADDR addr)
6193 int address_size = remote_address_size;
6195 /* If "remoteaddresssize" was not set, default to target address size. */
6197 address_size = gdbarch_addr_bit (target_gdbarch);
6199 if (address_size > 0
6200 && address_size < (sizeof (ULONGEST) * 8))
6202 /* Only create a mask when that mask can safely be constructed
6203 in a ULONGEST variable. */
6206 mask = (mask << address_size) - 1;
6212 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
6213 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
6214 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
6215 (which may be more than *OUT_LEN due to escape characters). The
6216 total number of bytes in the output buffer will be at most
6220 remote_escape_output (const gdb_byte *buffer, int len,
6221 gdb_byte *out_buf, int *out_len,
6224 int input_index, output_index;
6227 for (input_index = 0; input_index < len; input_index++)
6229 gdb_byte b = buffer[input_index];
6231 if (b == '$' || b == '#' || b == '}')
6233 /* These must be escaped. */
6234 if (output_index + 2 > out_maxlen)
6236 out_buf[output_index++] = '}';
6237 out_buf[output_index++] = b ^ 0x20;
6241 if (output_index + 1 > out_maxlen)
6243 out_buf[output_index++] = b;
6247 *out_len = input_index;
6248 return output_index;
6251 /* Convert BUFFER, escaped data LEN bytes long, into binary data
6252 in OUT_BUF. Return the number of bytes written to OUT_BUF.
6253 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
6255 This function reverses remote_escape_output. It allows more
6256 escaped characters than that function does, in particular because
6257 '*' must be escaped to avoid the run-length encoding processing
6258 in reading packets. */
6261 remote_unescape_input (const gdb_byte *buffer, int len,
6262 gdb_byte *out_buf, int out_maxlen)
6264 int input_index, output_index;
6269 for (input_index = 0; input_index < len; input_index++)
6271 gdb_byte b = buffer[input_index];
6273 if (output_index + 1 > out_maxlen)
6275 warning (_("Received too much data from remote target;"
6276 " ignoring overflow."));
6277 return output_index;
6282 out_buf[output_index++] = b ^ 0x20;
6288 out_buf[output_index++] = b;
6292 error (_("Unmatched escape character in target response."));
6294 return output_index;
6297 /* Determine whether the remote target supports binary downloading.
6298 This is accomplished by sending a no-op memory write of zero length
6299 to the target at the specified address. It does not suffice to send
6300 the whole packet, since many stubs strip the eighth bit and
6301 subsequently compute a wrong checksum, which causes real havoc with
6304 NOTE: This can still lose if the serial line is not eight-bit
6305 clean. In cases like this, the user should clear "remote
6309 check_binary_download (CORE_ADDR addr)
6311 struct remote_state *rs = get_remote_state ();
6313 switch (remote_protocol_packets[PACKET_X].support)
6315 case PACKET_DISABLE:
6319 case PACKET_SUPPORT_UNKNOWN:
6325 p += hexnumstr (p, (ULONGEST) addr);
6327 p += hexnumstr (p, (ULONGEST) 0);
6331 putpkt_binary (rs->buf, (int) (p - rs->buf));
6332 getpkt (&rs->buf, &rs->buf_size, 0);
6334 if (rs->buf[0] == '\0')
6337 fprintf_unfiltered (gdb_stdlog,
6338 "binary downloading NOT "
6339 "supported by target\n");
6340 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6345 fprintf_unfiltered (gdb_stdlog,
6346 "binary downloading supported by target\n");
6347 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6354 /* Write memory data directly to the remote machine.
6355 This does not inform the data cache; the data cache uses this.
6356 HEADER is the starting part of the packet.
6357 MEMADDR is the address in the remote memory space.
6358 MYADDR is the address of the buffer in our space.
6359 LEN is the number of bytes.
6360 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6361 should send data as binary ('X'), or hex-encoded ('M').
6363 The function creates packet of the form
6364 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6366 where encoding of <DATA> is termined by PACKET_FORMAT.
6368 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6371 Returns the number of bytes transferred, or 0 (setting errno) for
6372 error. Only transfer a single packet. */
6375 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6376 const gdb_byte *myaddr, int len,
6377 char packet_format, int use_length)
6379 struct remote_state *rs = get_remote_state ();
6389 if (packet_format != 'X' && packet_format != 'M')
6390 internal_error (__FILE__, __LINE__,
6391 _("remote_write_bytes_aux: bad packet format"));
6396 payload_size = get_memory_write_packet_size ();
6398 /* The packet buffer will be large enough for the payload;
6399 get_memory_packet_size ensures this. */
6402 /* Compute the size of the actual payload by subtracting out the
6403 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6405 payload_size -= strlen ("$,:#NN");
6407 /* The comma won't be used. */
6409 header_length = strlen (header);
6410 payload_size -= header_length;
6411 payload_size -= hexnumlen (memaddr);
6413 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
6415 strcat (rs->buf, header);
6416 p = rs->buf + strlen (header);
6418 /* Compute a best guess of the number of bytes actually transfered. */
6419 if (packet_format == 'X')
6421 /* Best guess at number of bytes that will fit. */
6422 todo = min (len, payload_size);
6424 payload_size -= hexnumlen (todo);
6425 todo = min (todo, payload_size);
6429 /* Num bytes that will fit. */
6430 todo = min (len, payload_size / 2);
6432 payload_size -= hexnumlen (todo);
6433 todo = min (todo, payload_size / 2);
6437 internal_error (__FILE__, __LINE__,
6438 _("minimum packet size too small to write data"));
6440 /* If we already need another packet, then try to align the end
6441 of this packet to a useful boundary. */
6442 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6443 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6445 /* Append "<memaddr>". */
6446 memaddr = remote_address_masked (memaddr);
6447 p += hexnumstr (p, (ULONGEST) memaddr);
6454 /* Append <len>. Retain the location/size of <len>. It may need to
6455 be adjusted once the packet body has been created. */
6457 plenlen = hexnumstr (p, (ULONGEST) todo);
6465 /* Append the packet body. */
6466 if (packet_format == 'X')
6468 /* Binary mode. Send target system values byte by byte, in
6469 increasing byte addresses. Only escape certain critical
6471 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
6474 /* If not all TODO bytes fit, then we'll need another packet. Make
6475 a second try to keep the end of the packet aligned. Don't do
6476 this if the packet is tiny. */
6477 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6481 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6483 if (new_nr_bytes != nr_bytes)
6484 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6489 p += payload_length;
6490 if (use_length && nr_bytes < todo)
6492 /* Escape chars have filled up the buffer prematurely,
6493 and we have actually sent fewer bytes than planned.
6494 Fix-up the length field of the packet. Use the same
6495 number of characters as before. */
6496 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6497 *plen = ':'; /* overwrite \0 from hexnumnstr() */
6502 /* Normal mode: Send target system values byte by byte, in
6503 increasing byte addresses. Each byte is encoded as a two hex
6505 nr_bytes = bin2hex (myaddr, p, todo);
6509 putpkt_binary (rs->buf, (int) (p - rs->buf));
6510 getpkt (&rs->buf, &rs->buf_size, 0);
6512 if (rs->buf[0] == 'E')
6514 /* There is no correspondance between what the remote protocol
6515 uses for errors and errno codes. We would like a cleaner way
6516 of representing errors (big enough to include errno codes,
6517 bfd_error codes, and others). But for now just return EIO. */
6522 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6523 fewer bytes than we'd planned. */
6527 /* Write memory data directly to the remote machine.
6528 This does not inform the data cache; the data cache uses this.
6529 MEMADDR is the address in the remote memory space.
6530 MYADDR is the address of the buffer in our space.
6531 LEN is the number of bytes.
6533 Returns number of bytes transferred, or 0 (setting errno) for
6534 error. Only transfer a single packet. */
6537 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
6539 char *packet_format = 0;
6541 /* Check whether the target supports binary download. */
6542 check_binary_download (memaddr);
6544 switch (remote_protocol_packets[PACKET_X].support)
6547 packet_format = "X";
6549 case PACKET_DISABLE:
6550 packet_format = "M";
6552 case PACKET_SUPPORT_UNKNOWN:
6553 internal_error (__FILE__, __LINE__,
6554 _("remote_write_bytes: bad internal state"));
6556 internal_error (__FILE__, __LINE__, _("bad switch"));
6559 return remote_write_bytes_aux (packet_format,
6560 memaddr, myaddr, len, packet_format[0], 1);
6563 /* Read memory data directly from the remote machine.
6564 This does not use the data cache; the data cache uses this.
6565 MEMADDR is the address in the remote memory space.
6566 MYADDR is the address of the buffer in our space.
6567 LEN is the number of bytes.
6569 Returns number of bytes transferred, or 0 for error. */
6572 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
6574 struct remote_state *rs = get_remote_state ();
6575 int max_buf_size; /* Max size of packet output buffer. */
6583 max_buf_size = get_memory_read_packet_size ();
6584 /* The packet buffer will be large enough for the payload;
6585 get_memory_packet_size ensures this. */
6587 /* Number if bytes that will fit. */
6588 todo = min (len, max_buf_size / 2);
6590 /* Construct "m"<memaddr>","<len>". */
6591 memaddr = remote_address_masked (memaddr);
6594 p += hexnumstr (p, (ULONGEST) memaddr);
6596 p += hexnumstr (p, (ULONGEST) todo);
6599 getpkt (&rs->buf, &rs->buf_size, 0);
6600 if (rs->buf[0] == 'E'
6601 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6602 && rs->buf[3] == '\0')
6604 /* There is no correspondance between what the remote protocol
6605 uses for errors and errno codes. We would like a cleaner way
6606 of representing errors (big enough to include errno codes,
6607 bfd_error codes, and others). But for now just return
6612 /* Reply describes memory byte by byte, each byte encoded as two hex
6615 i = hex2bin (p, myaddr, todo);
6616 /* Return what we have. Let higher layers handle partial reads. */
6621 /* Remote notification handler. */
6624 handle_notification (char *buf, size_t length)
6626 if (strncmp (buf, "Stop:", 5) == 0)
6628 if (pending_stop_reply)
6630 /* We've already parsed the in-flight stop-reply, but the
6631 stub for some reason thought we didn't, possibly due to
6632 timeout on its side. Just ignore it. */
6634 fprintf_unfiltered (gdb_stdlog, "ignoring resent notification\n");
6638 struct cleanup *old_chain;
6639 struct stop_reply *reply = stop_reply_xmalloc ();
6641 old_chain = make_cleanup (do_stop_reply_xfree, reply);
6643 remote_parse_stop_reply (buf + 5, reply);
6645 discard_cleanups (old_chain);
6647 /* Be careful to only set it after parsing, since an error
6648 may be thrown then. */
6649 pending_stop_reply = reply;
6651 /* Notify the event loop there's a stop reply to acknowledge
6652 and that there may be more events to fetch. */
6653 mark_async_event_handler (remote_async_get_pending_events_token);
6656 fprintf_unfiltered (gdb_stdlog, "stop notification captured\n");
6660 /* We ignore notifications we don't recognize, for compatibility
6661 with newer stubs. */
6666 /* Read or write LEN bytes from inferior memory at MEMADDR,
6667 transferring to or from debugger address BUFFER. Write to inferior
6668 if SHOULD_WRITE is nonzero. Returns length of data written or
6669 read; 0 for error. TARGET is unused. */
6672 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
6673 int should_write, struct mem_attrib *attrib,
6674 struct target_ops *target)
6678 set_remote_traceframe ();
6679 set_general_thread (inferior_ptid);
6682 res = remote_write_bytes (mem_addr, buffer, mem_len);
6684 res = remote_read_bytes (mem_addr, buffer, mem_len);
6689 /* Sends a packet with content determined by the printf format string
6690 FORMAT and the remaining arguments, then gets the reply. Returns
6691 whether the packet was a success, a failure, or unknown. */
6693 static enum packet_result
6694 remote_send_printf (const char *format, ...)
6696 struct remote_state *rs = get_remote_state ();
6697 int max_size = get_remote_packet_size ();
6700 va_start (ap, format);
6703 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
6704 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
6706 if (putpkt (rs->buf) < 0)
6707 error (_("Communication problem with target."));
6710 getpkt (&rs->buf, &rs->buf_size, 0);
6712 return packet_check_result (rs->buf);
6716 restore_remote_timeout (void *p)
6718 int value = *(int *)p;
6720 remote_timeout = value;
6723 /* Flash writing can take quite some time. We'll set
6724 effectively infinite timeout for flash operations.
6725 In future, we'll need to decide on a better approach. */
6726 static const int remote_flash_timeout = 1000;
6729 remote_flash_erase (struct target_ops *ops,
6730 ULONGEST address, LONGEST length)
6732 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
6733 int saved_remote_timeout = remote_timeout;
6734 enum packet_result ret;
6735 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6736 &saved_remote_timeout);
6738 remote_timeout = remote_flash_timeout;
6740 ret = remote_send_printf ("vFlashErase:%s,%s",
6741 phex (address, addr_size),
6745 case PACKET_UNKNOWN:
6746 error (_("Remote target does not support flash erase"));
6748 error (_("Error erasing flash with vFlashErase packet"));
6753 do_cleanups (back_to);
6757 remote_flash_write (struct target_ops *ops,
6758 ULONGEST address, LONGEST length,
6759 const gdb_byte *data)
6761 int saved_remote_timeout = remote_timeout;
6763 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6764 &saved_remote_timeout);
6766 remote_timeout = remote_flash_timeout;
6767 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
6768 do_cleanups (back_to);
6774 remote_flash_done (struct target_ops *ops)
6776 int saved_remote_timeout = remote_timeout;
6778 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6779 &saved_remote_timeout);
6781 remote_timeout = remote_flash_timeout;
6782 ret = remote_send_printf ("vFlashDone");
6783 do_cleanups (back_to);
6787 case PACKET_UNKNOWN:
6788 error (_("Remote target does not support vFlashDone"));
6790 error (_("Error finishing flash operation"));
6797 remote_files_info (struct target_ops *ignore)
6799 puts_filtered ("Debugging a target over a serial line.\n");
6802 /* Stuff for dealing with the packets which are part of this protocol.
6803 See comment at top of file for details. */
6805 /* Read a single character from the remote end. */
6808 readchar (int timeout)
6812 ch = serial_readchar (remote_desc, timeout);
6817 switch ((enum serial_rc) ch)
6821 error (_("Remote connection closed"));
6825 perror_with_name (_("Remote communication error. "
6826 "Target disconnected."));
6828 case SERIAL_TIMEOUT:
6834 /* Send the command in *BUF to the remote machine, and read the reply
6835 into *BUF. Report an error if we get an error reply. Resize
6836 *BUF using xrealloc if necessary to hold the result, and update
6840 remote_send (char **buf,
6844 getpkt (buf, sizeof_buf, 0);
6846 if ((*buf)[0] == 'E')
6847 error (_("Remote failure reply: %s"), *buf);
6850 /* Return a pointer to an xmalloc'ed string representing an escaped
6851 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
6852 etc. The caller is responsible for releasing the returned
6856 escape_buffer (const char *buf, int n)
6858 struct cleanup *old_chain;
6859 struct ui_file *stb;
6862 stb = mem_fileopen ();
6863 old_chain = make_cleanup_ui_file_delete (stb);
6865 fputstrn_unfiltered (buf, n, 0, stb);
6866 str = ui_file_xstrdup (stb, NULL);
6867 do_cleanups (old_chain);
6871 /* Display a null-terminated packet on stdout, for debugging, using C
6875 print_packet (char *buf)
6877 puts_filtered ("\"");
6878 fputstr_filtered (buf, '"', gdb_stdout);
6879 puts_filtered ("\"");
6885 return putpkt_binary (buf, strlen (buf));
6888 /* Send a packet to the remote machine, with error checking. The data
6889 of the packet is in BUF. The string in BUF can be at most
6890 get_remote_packet_size () - 5 to account for the $, # and checksum,
6891 and for a possible /0 if we are debugging (remote_debug) and want
6892 to print the sent packet as a string. */
6895 putpkt_binary (char *buf, int cnt)
6897 struct remote_state *rs = get_remote_state ();
6899 unsigned char csum = 0;
6900 char *buf2 = alloca (cnt + 6);
6906 /* Catch cases like trying to read memory or listing threads while
6907 we're waiting for a stop reply. The remote server wouldn't be
6908 ready to handle this request, so we'd hang and timeout. We don't
6909 have to worry about this in synchronous mode, because in that
6910 case it's not possible to issue a command while the target is
6911 running. This is not a problem in non-stop mode, because in that
6912 case, the stub is always ready to process serial input. */
6913 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
6914 error (_("Cannot execute this command while the target is running."));
6916 /* We're sending out a new packet. Make sure we don't look at a
6917 stale cached response. */
6918 rs->cached_wait_status = 0;
6920 /* Copy the packet into buffer BUF2, encapsulating it
6921 and giving it a checksum. */
6926 for (i = 0; i < cnt; i++)
6932 *p++ = tohex ((csum >> 4) & 0xf);
6933 *p++ = tohex (csum & 0xf);
6935 /* Send it over and over until we get a positive ack. */
6939 int started_error_output = 0;
6943 struct cleanup *old_chain;
6947 str = escape_buffer (buf2, p - buf2);
6948 old_chain = make_cleanup (xfree, str);
6949 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
6950 gdb_flush (gdb_stdlog);
6951 do_cleanups (old_chain);
6953 if (serial_write (remote_desc, buf2, p - buf2))
6954 perror_with_name (_("putpkt: write failed"));
6956 /* If this is a no acks version of the remote protocol, send the
6957 packet and move on. */
6961 /* Read until either a timeout occurs (-2) or '+' is read.
6962 Handle any notification that arrives in the mean time. */
6965 ch = readchar (remote_timeout);
6973 case SERIAL_TIMEOUT:
6976 if (started_error_output)
6978 putchar_unfiltered ('\n');
6979 started_error_output = 0;
6988 fprintf_unfiltered (gdb_stdlog, "Ack\n");
6992 fprintf_unfiltered (gdb_stdlog, "Nak\n");
6994 case SERIAL_TIMEOUT:
6998 break; /* Retransmit buffer. */
7002 fprintf_unfiltered (gdb_stdlog,
7003 "Packet instead of Ack, ignoring it\n");
7004 /* It's probably an old response sent because an ACK
7005 was lost. Gobble up the packet and ack it so it
7006 doesn't get retransmitted when we resend this
7009 serial_write (remote_desc, "+", 1);
7010 continue; /* Now, go look for +. */
7017 /* If we got a notification, handle it, and go back to looking
7019 /* We've found the start of a notification. Now
7020 collect the data. */
7021 val = read_frame (&rs->buf, &rs->buf_size);
7026 struct cleanup *old_chain;
7029 str = escape_buffer (rs->buf, val);
7030 old_chain = make_cleanup (xfree, str);
7031 fprintf_unfiltered (gdb_stdlog,
7032 " Notification received: %s\n",
7034 do_cleanups (old_chain);
7036 handle_notification (rs->buf, val);
7037 /* We're in sync now, rewait for the ack. */
7044 if (!started_error_output)
7046 started_error_output = 1;
7047 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7049 fputc_unfiltered (ch & 0177, gdb_stdlog);
7050 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7059 if (!started_error_output)
7061 started_error_output = 1;
7062 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7064 fputc_unfiltered (ch & 0177, gdb_stdlog);
7068 break; /* Here to retransmit. */
7072 /* This is wrong. If doing a long backtrace, the user should be
7073 able to get out next time we call QUIT, without anything as
7074 violent as interrupt_query. If we want to provide a way out of
7075 here without getting to the next QUIT, it should be based on
7076 hitting ^C twice as in remote_wait. */
7087 /* Come here after finding the start of a frame when we expected an
7088 ack. Do our best to discard the rest of this packet. */
7097 c = readchar (remote_timeout);
7100 case SERIAL_TIMEOUT:
7101 /* Nothing we can do. */
7104 /* Discard the two bytes of checksum and stop. */
7105 c = readchar (remote_timeout);
7107 c = readchar (remote_timeout);
7110 case '*': /* Run length encoding. */
7111 /* Discard the repeat count. */
7112 c = readchar (remote_timeout);
7117 /* A regular character. */
7123 /* Come here after finding the start of the frame. Collect the rest
7124 into *BUF, verifying the checksum, length, and handling run-length
7125 compression. NUL terminate the buffer. If there is not enough room,
7126 expand *BUF using xrealloc.
7128 Returns -1 on error, number of characters in buffer (ignoring the
7129 trailing NULL) on success. (could be extended to return one of the
7130 SERIAL status indications). */
7133 read_frame (char **buf_p,
7140 struct remote_state *rs = get_remote_state ();
7147 c = readchar (remote_timeout);
7150 case SERIAL_TIMEOUT:
7152 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7156 fputs_filtered ("Saw new packet start in middle of old one\n",
7158 return -1; /* Start a new packet, count retries. */
7161 unsigned char pktcsum;
7167 check_0 = readchar (remote_timeout);
7169 check_1 = readchar (remote_timeout);
7171 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7174 fputs_filtered ("Timeout in checksum, retrying\n",
7178 else if (check_0 < 0 || check_1 < 0)
7181 fputs_filtered ("Communication error in checksum\n",
7186 /* Don't recompute the checksum; with no ack packets we
7187 don't have any way to indicate a packet retransmission
7192 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7193 if (csum == pktcsum)
7198 struct cleanup *old_chain;
7201 str = escape_buffer (buf, bc);
7202 old_chain = make_cleanup (xfree, str);
7203 fprintf_unfiltered (gdb_stdlog,
7204 "Bad checksum, sentsum=0x%x, "
7205 "csum=0x%x, buf=%s\n",
7206 pktcsum, csum, str);
7207 do_cleanups (old_chain);
7209 /* Number of characters in buffer ignoring trailing
7213 case '*': /* Run length encoding. */
7218 c = readchar (remote_timeout);
7220 repeat = c - ' ' + 3; /* Compute repeat count. */
7222 /* The character before ``*'' is repeated. */
7224 if (repeat > 0 && repeat <= 255 && bc > 0)
7226 if (bc + repeat - 1 >= *sizeof_buf - 1)
7228 /* Make some more room in the buffer. */
7229 *sizeof_buf += repeat;
7230 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7234 memset (&buf[bc], buf[bc - 1], repeat);
7240 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
7244 if (bc >= *sizeof_buf - 1)
7246 /* Make some more room in the buffer. */
7248 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7259 /* Read a packet from the remote machine, with error checking, and
7260 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7261 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7262 rather than timing out; this is used (in synchronous mode) to wait
7263 for a target that is is executing user code to stop. */
7264 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7265 don't have to change all the calls to getpkt to deal with the
7266 return value, because at the moment I don't know what the right
7267 thing to do it for those. */
7275 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7279 /* Read a packet from the remote machine, with error checking, and
7280 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7281 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7282 rather than timing out; this is used (in synchronous mode) to wait
7283 for a target that is is executing user code to stop. If FOREVER ==
7284 0, this function is allowed to time out gracefully and return an
7285 indication of this to the caller. Otherwise return the number of
7286 bytes read. If EXPECTING_NOTIF, consider receiving a notification
7287 enough reason to return to the caller. */
7290 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7291 int expecting_notif)
7293 struct remote_state *rs = get_remote_state ();
7299 /* We're reading a new response. Make sure we don't look at a
7300 previously cached response. */
7301 rs->cached_wait_status = 0;
7303 strcpy (*buf, "timeout");
7306 timeout = watchdog > 0 ? watchdog : -1;
7307 else if (expecting_notif)
7308 timeout = 0; /* There should already be a char in the buffer. If
7311 timeout = remote_timeout;
7315 /* Process any number of notifications, and then return when
7319 /* If we get a timeout or bad checksm, retry up to MAX_TRIES
7321 for (tries = 1; tries <= MAX_TRIES; tries++)
7323 /* This can loop forever if the remote side sends us
7324 characters continuously, but if it pauses, we'll get
7325 SERIAL_TIMEOUT from readchar because of timeout. Then
7326 we'll count that as a retry.
7328 Note that even when forever is set, we will only wait
7329 forever prior to the start of a packet. After that, we
7330 expect characters to arrive at a brisk pace. They should
7331 show up within remote_timeout intervals. */
7333 c = readchar (timeout);
7334 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
7336 if (c == SERIAL_TIMEOUT)
7338 if (expecting_notif)
7339 return -1; /* Don't complain, it's normal to not get
7340 anything in this case. */
7342 if (forever) /* Watchdog went off? Kill the target. */
7346 error (_("Watchdog timeout has expired. Target detached."));
7349 fputs_filtered ("Timed out.\n", gdb_stdlog);
7353 /* We've found the start of a packet or notification.
7354 Now collect the data. */
7355 val = read_frame (buf, sizeof_buf);
7360 serial_write (remote_desc, "-", 1);
7363 if (tries > MAX_TRIES)
7365 /* We have tried hard enough, and just can't receive the
7366 packet/notification. Give up. */
7367 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
7369 /* Skip the ack char if we're in no-ack mode. */
7370 if (!rs->noack_mode)
7371 serial_write (remote_desc, "+", 1);
7375 /* If we got an ordinary packet, return that to our caller. */
7380 struct cleanup *old_chain;
7383 str = escape_buffer (*buf, val);
7384 old_chain = make_cleanup (xfree, str);
7385 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7386 do_cleanups (old_chain);
7389 /* Skip the ack char if we're in no-ack mode. */
7390 if (!rs->noack_mode)
7391 serial_write (remote_desc, "+", 1);
7395 /* If we got a notification, handle it, and go back to looking
7399 gdb_assert (c == '%');
7403 struct cleanup *old_chain;
7406 str = escape_buffer (*buf, val);
7407 old_chain = make_cleanup (xfree, str);
7408 fprintf_unfiltered (gdb_stdlog,
7409 " Notification received: %s\n",
7411 do_cleanups (old_chain);
7414 handle_notification (*buf, val);
7416 /* Notifications require no acknowledgement. */
7418 if (expecting_notif)
7425 getpkt_sane (char **buf, long *sizeof_buf, int forever)
7427 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0);
7431 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever)
7433 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1);
7437 /* A helper function that just calls putpkt; for type correctness. */
7440 putpkt_for_catch_errors (void *arg)
7442 return putpkt (arg);
7446 remote_kill (struct target_ops *ops)
7448 /* Use catch_errors so the user can quit from gdb even when we
7449 aren't on speaking terms with the remote system. */
7450 catch_errors (putpkt_for_catch_errors, "k", "", RETURN_MASK_ERROR);
7452 /* Don't wait for it to die. I'm not really sure it matters whether
7453 we do or not. For the existing stubs, kill is a noop. */
7454 target_mourn_inferior ();
7458 remote_vkill (int pid, struct remote_state *rs)
7460 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7463 /* Tell the remote target to detach. */
7464 sprintf (rs->buf, "vKill;%x", pid);
7466 getpkt (&rs->buf, &rs->buf_size, 0);
7468 if (packet_ok (rs->buf,
7469 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
7471 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7478 extended_remote_kill (struct target_ops *ops)
7481 int pid = ptid_get_pid (inferior_ptid);
7482 struct remote_state *rs = get_remote_state ();
7484 res = remote_vkill (pid, rs);
7485 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
7487 /* Don't try 'k' on a multi-process aware stub -- it has no way
7488 to specify the pid. */
7492 getpkt (&rs->buf, &rs->buf_size, 0);
7493 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7496 /* Don't wait for it to die. I'm not really sure it matters whether
7497 we do or not. For the existing stubs, kill is a noop. */
7503 error (_("Can't kill process"));
7505 target_mourn_inferior ();
7509 remote_mourn (struct target_ops *ops)
7511 remote_mourn_1 (ops);
7514 /* Worker function for remote_mourn. */
7516 remote_mourn_1 (struct target_ops *target)
7518 unpush_target (target);
7520 /* remote_close takes care of doing most of the clean up. */
7521 generic_mourn_inferior ();
7525 extended_remote_mourn_1 (struct target_ops *target)
7527 struct remote_state *rs = get_remote_state ();
7529 /* In case we got here due to an error, but we're going to stay
7531 rs->waiting_for_stop_reply = 0;
7533 /* We're no longer interested in these events. */
7534 discard_pending_stop_replies (ptid_get_pid (inferior_ptid));
7536 /* If the current general thread belonged to the process we just
7537 detached from or has exited, the remote side current general
7538 thread becomes undefined. Considering a case like this:
7540 - We just got here due to a detach.
7541 - The process that we're detaching from happens to immediately
7542 report a global breakpoint being hit in non-stop mode, in the
7543 same thread we had selected before.
7544 - GDB attaches to this process again.
7545 - This event happens to be the next event we handle.
7547 GDB would consider that the current general thread didn't need to
7548 be set on the stub side (with Hg), since for all it knew,
7549 GENERAL_THREAD hadn't changed.
7551 Notice that although in all-stop mode, the remote server always
7552 sets the current thread to the thread reporting the stop event,
7553 that doesn't happen in non-stop mode; in non-stop, the stub *must
7554 not* change the current thread when reporting a breakpoint hit,
7555 due to the decoupling of event reporting and event handling.
7557 To keep things simple, we always invalidate our notion of the
7559 record_currthread (minus_one_ptid);
7561 /* Unlike "target remote", we do not want to unpush the target; then
7562 the next time the user says "run", we won't be connected. */
7564 /* Call common code to mark the inferior as not running. */
7565 generic_mourn_inferior ();
7567 if (!have_inferiors ())
7569 if (!remote_multi_process_p (rs))
7571 /* Check whether the target is running now - some remote stubs
7572 automatically restart after kill. */
7574 getpkt (&rs->buf, &rs->buf_size, 0);
7576 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7578 /* Assume that the target has been restarted. Set
7579 inferior_ptid so that bits of core GDB realizes
7580 there's something here, e.g., so that the user can
7581 say "kill" again. */
7582 inferior_ptid = magic_null_ptid;
7589 extended_remote_mourn (struct target_ops *ops)
7591 extended_remote_mourn_1 (ops);
7595 extended_remote_supports_disable_randomization (void)
7597 return (remote_protocol_packets[PACKET_QDisableRandomization].support
7602 extended_remote_disable_randomization (int val)
7604 struct remote_state *rs = get_remote_state ();
7607 sprintf (rs->buf, "QDisableRandomization:%x", val);
7609 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
7611 error (_("Target does not support QDisableRandomization."));
7612 if (strcmp (reply, "OK") != 0)
7613 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
7617 extended_remote_run (char *args)
7619 struct remote_state *rs = get_remote_state ();
7622 /* If the user has disabled vRun support, or we have detected that
7623 support is not available, do not try it. */
7624 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7627 strcpy (rs->buf, "vRun;");
7628 len = strlen (rs->buf);
7630 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
7631 error (_("Remote file name too long for run packet"));
7632 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
7634 gdb_assert (args != NULL);
7637 struct cleanup *back_to;
7641 argv = gdb_buildargv (args);
7642 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
7643 for (i = 0; argv[i] != NULL; i++)
7645 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
7646 error (_("Argument list too long for run packet"));
7647 rs->buf[len++] = ';';
7648 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
7650 do_cleanups (back_to);
7653 rs->buf[len++] = '\0';
7656 getpkt (&rs->buf, &rs->buf_size, 0);
7658 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
7660 /* We have a wait response; we don't need it, though. All is well. */
7663 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7664 /* It wasn't disabled before, but it is now. */
7668 if (remote_exec_file[0] == '\0')
7669 error (_("Running the default executable on the remote target failed; "
7670 "try \"set remote exec-file\"?"));
7672 error (_("Running \"%s\" on the remote target failed"),
7677 /* In the extended protocol we want to be able to do things like
7678 "run" and have them basically work as expected. So we need
7679 a special create_inferior function. We support changing the
7680 executable file and the command line arguments, but not the
7684 extended_remote_create_inferior_1 (char *exec_file, char *args,
7685 char **env, int from_tty)
7687 /* If running asynchronously, register the target file descriptor
7688 with the event loop. */
7689 if (target_can_async_p ())
7690 target_async (inferior_event_handler, 0);
7692 /* Disable address space randomization if requested (and supported). */
7693 if (extended_remote_supports_disable_randomization ())
7694 extended_remote_disable_randomization (disable_randomization);
7696 /* Now restart the remote server. */
7697 if (extended_remote_run (args) == -1)
7699 /* vRun was not supported. Fail if we need it to do what the
7701 if (remote_exec_file[0])
7702 error (_("Remote target does not support \"set remote exec-file\""));
7704 error (_("Remote target does not support \"set args\" or run <ARGS>"));
7706 /* Fall back to "R". */
7707 extended_remote_restart ();
7710 if (!have_inferiors ())
7712 /* Clean up from the last time we ran, before we mark the target
7713 running again. This will mark breakpoints uninserted, and
7714 get_offsets may insert breakpoints. */
7715 init_thread_list ();
7716 init_wait_for_inferior ();
7719 add_current_inferior_and_thread ();
7721 /* Get updated offsets, if the stub uses qOffsets. */
7726 extended_remote_create_inferior (struct target_ops *ops,
7727 char *exec_file, char *args,
7728 char **env, int from_tty)
7730 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
7734 /* Given a location's target info BP_TGT and the packet buffer BUF, output
7735 the list of conditions (in agent expression bytecode format), if any, the
7736 target needs to evaluate. The output is placed into the packet buffer
7740 remote_add_target_side_condition (struct gdbarch *gdbarch,
7741 struct bp_target_info *bp_tgt, char *buf)
7743 struct agent_expr *aexpr = NULL;
7746 char *buf_start = buf;
7748 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
7751 buf += strlen (buf);
7752 sprintf (buf, "%s", ";");
7755 /* Send conditions to the target and free the vector. */
7757 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
7760 sprintf (buf, "X%x,", aexpr->len);
7761 buf += strlen (buf);
7762 for (i = 0; i < aexpr->len; ++i)
7763 buf = pack_hex_byte (buf, aexpr->buf[i]);
7767 VEC_free (agent_expr_p, bp_tgt->conditions);
7771 /* Insert a breakpoint. On targets that have software breakpoint
7772 support, we ask the remote target to do the work; on targets
7773 which don't, we insert a traditional memory breakpoint. */
7776 remote_insert_breakpoint (struct gdbarch *gdbarch,
7777 struct bp_target_info *bp_tgt)
7779 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
7780 If it succeeds, then set the support to PACKET_ENABLE. If it
7781 fails, and the user has explicitly requested the Z support then
7782 report an error, otherwise, mark it disabled and go on. */
7784 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
7786 CORE_ADDR addr = bp_tgt->placed_address;
7787 struct remote_state *rs;
7790 struct condition_list *cond = NULL;
7792 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
7794 rs = get_remote_state ();
7800 addr = (ULONGEST) remote_address_masked (addr);
7801 p += hexnumstr (p, addr);
7802 sprintf (p, ",%d", bpsize);
7804 if (remote_supports_cond_breakpoints ())
7805 remote_add_target_side_condition (gdbarch, bp_tgt, p);
7808 getpkt (&rs->buf, &rs->buf_size, 0);
7810 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
7815 bp_tgt->placed_address = addr;
7816 bp_tgt->placed_size = bpsize;
7818 case PACKET_UNKNOWN:
7823 return memory_insert_breakpoint (gdbarch, bp_tgt);
7827 remote_remove_breakpoint (struct gdbarch *gdbarch,
7828 struct bp_target_info *bp_tgt)
7830 CORE_ADDR addr = bp_tgt->placed_address;
7831 struct remote_state *rs = get_remote_state ();
7833 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
7841 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
7842 p += hexnumstr (p, addr);
7843 sprintf (p, ",%d", bp_tgt->placed_size);
7846 getpkt (&rs->buf, &rs->buf_size, 0);
7848 return (rs->buf[0] == 'E');
7851 return memory_remove_breakpoint (gdbarch, bp_tgt);
7855 watchpoint_to_Z_packet (int type)
7860 return Z_PACKET_WRITE_WP;
7863 return Z_PACKET_READ_WP;
7866 return Z_PACKET_ACCESS_WP;
7869 internal_error (__FILE__, __LINE__,
7870 _("hw_bp_to_z: bad watchpoint type %d"), type);
7875 remote_insert_watchpoint (CORE_ADDR addr, int len, int type,
7876 struct expression *cond)
7878 struct remote_state *rs = get_remote_state ();
7880 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
7882 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
7885 sprintf (rs->buf, "Z%x,", packet);
7886 p = strchr (rs->buf, '\0');
7887 addr = remote_address_masked (addr);
7888 p += hexnumstr (p, (ULONGEST) addr);
7889 sprintf (p, ",%x", len);
7892 getpkt (&rs->buf, &rs->buf_size, 0);
7894 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
7898 case PACKET_UNKNOWN:
7903 internal_error (__FILE__, __LINE__,
7904 _("remote_insert_watchpoint: reached end of function"));
7908 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
7909 CORE_ADDR start, int length)
7911 CORE_ADDR diff = remote_address_masked (addr - start);
7913 return diff < length;
7918 remote_remove_watchpoint (CORE_ADDR addr, int len, int type,
7919 struct expression *cond)
7921 struct remote_state *rs = get_remote_state ();
7923 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
7925 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
7928 sprintf (rs->buf, "z%x,", packet);
7929 p = strchr (rs->buf, '\0');
7930 addr = remote_address_masked (addr);
7931 p += hexnumstr (p, (ULONGEST) addr);
7932 sprintf (p, ",%x", len);
7934 getpkt (&rs->buf, &rs->buf_size, 0);
7936 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
7939 case PACKET_UNKNOWN:
7944 internal_error (__FILE__, __LINE__,
7945 _("remote_remove_watchpoint: reached end of function"));
7949 int remote_hw_watchpoint_limit = -1;
7950 int remote_hw_watchpoint_length_limit = -1;
7951 int remote_hw_breakpoint_limit = -1;
7954 remote_region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
7956 if (remote_hw_watchpoint_length_limit == 0)
7958 else if (remote_hw_watchpoint_length_limit < 0)
7960 else if (len <= remote_hw_watchpoint_length_limit)
7967 remote_check_watch_resources (int type, int cnt, int ot)
7969 if (type == bp_hardware_breakpoint)
7971 if (remote_hw_breakpoint_limit == 0)
7973 else if (remote_hw_breakpoint_limit < 0)
7975 else if (cnt <= remote_hw_breakpoint_limit)
7980 if (remote_hw_watchpoint_limit == 0)
7982 else if (remote_hw_watchpoint_limit < 0)
7986 else if (cnt <= remote_hw_watchpoint_limit)
7993 remote_stopped_by_watchpoint (void)
7995 return remote_stopped_by_watchpoint_p;
7999 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
8003 if (remote_stopped_by_watchpoint ())
8005 *addr_p = remote_watch_data_address;
8014 remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
8015 struct bp_target_info *bp_tgt)
8018 struct remote_state *rs;
8021 /* The length field should be set to the size of a breakpoint
8022 instruction, even though we aren't inserting one ourselves. */
8024 gdbarch_remote_breakpoint_from_pc
8025 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
8027 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
8030 rs = get_remote_state ();
8037 addr = remote_address_masked (bp_tgt->placed_address);
8038 p += hexnumstr (p, (ULONGEST) addr);
8039 sprintf (p, ",%x", bp_tgt->placed_size);
8041 if (remote_supports_cond_breakpoints ())
8042 remote_add_target_side_condition (gdbarch, bp_tgt, p);
8045 getpkt (&rs->buf, &rs->buf_size, 0);
8047 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8050 case PACKET_UNKNOWN:
8055 internal_error (__FILE__, __LINE__,
8056 _("remote_insert_hw_breakpoint: reached end of function"));
8061 remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
8062 struct bp_target_info *bp_tgt)
8065 struct remote_state *rs = get_remote_state ();
8068 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
8075 addr = remote_address_masked (bp_tgt->placed_address);
8076 p += hexnumstr (p, (ULONGEST) addr);
8077 sprintf (p, ",%x", bp_tgt->placed_size);
8080 getpkt (&rs->buf, &rs->buf_size, 0);
8082 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8085 case PACKET_UNKNOWN:
8090 internal_error (__FILE__, __LINE__,
8091 _("remote_remove_hw_breakpoint: reached end of function"));
8094 /* Table used by the crc32 function to calcuate the checksum. */
8096 static unsigned long crc32_table[256] =
8099 static unsigned long
8100 crc32 (const unsigned char *buf, int len, unsigned int crc)
8102 if (!crc32_table[1])
8104 /* Initialize the CRC table and the decoding table. */
8108 for (i = 0; i < 256; i++)
8110 for (c = i << 24, j = 8; j > 0; --j)
8111 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
8118 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
8124 /* Verify memory using the "qCRC:" request. */
8127 remote_verify_memory (struct target_ops *ops,
8128 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8130 struct remote_state *rs = get_remote_state ();
8131 unsigned long host_crc, target_crc;
8134 /* FIXME: assumes lma can fit into long. */
8135 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8136 (long) lma, (long) size);
8139 /* Be clever; compute the host_crc before waiting for target
8141 host_crc = crc32 (data, size, 0xffffffff);
8143 getpkt (&rs->buf, &rs->buf_size, 0);
8144 if (rs->buf[0] == 'E')
8147 if (rs->buf[0] != 'C')
8148 error (_("remote target does not support this operation"));
8150 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8151 target_crc = target_crc * 16 + fromhex (*tmp);
8153 return (host_crc == target_crc);
8156 /* compare-sections command
8158 With no arguments, compares each loadable section in the exec bfd
8159 with the same memory range on the target, and reports mismatches.
8160 Useful for verifying the image on the target against the exec file. */
8163 compare_sections_command (char *args, int from_tty)
8166 struct cleanup *old_chain;
8168 const char *sectname;
8176 error (_("command cannot be used without an exec file"));
8178 for (s = exec_bfd->sections; s; s = s->next)
8180 if (!(s->flags & SEC_LOAD))
8181 continue; /* Skip non-loadable section. */
8183 size = bfd_get_section_size (s);
8185 continue; /* Skip zero-length section. */
8187 sectname = bfd_get_section_name (exec_bfd, s);
8188 if (args && strcmp (args, sectname) != 0)
8189 continue; /* Not the section selected by user. */
8191 matched = 1; /* Do this section. */
8194 sectdata = xmalloc (size);
8195 old_chain = make_cleanup (xfree, sectdata);
8196 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
8198 res = target_verify_memory (sectdata, lma, size);
8201 error (_("target memory fault, section %s, range %s -- %s"), sectname,
8202 paddress (target_gdbarch, lma),
8203 paddress (target_gdbarch, lma + size));
8205 printf_filtered ("Section %s, range %s -- %s: ", sectname,
8206 paddress (target_gdbarch, lma),
8207 paddress (target_gdbarch, lma + size));
8209 printf_filtered ("matched.\n");
8212 printf_filtered ("MIS-MATCHED!\n");
8216 do_cleanups (old_chain);
8219 warning (_("One or more sections of the remote executable does not match\n\
8220 the loaded file\n"));
8221 if (args && !matched)
8222 printf_filtered (_("No loaded section named '%s'.\n"), args);
8225 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8226 into remote target. The number of bytes written to the remote
8227 target is returned, or -1 for error. */
8230 remote_write_qxfer (struct target_ops *ops, const char *object_name,
8231 const char *annex, const gdb_byte *writebuf,
8232 ULONGEST offset, LONGEST len,
8233 struct packet_config *packet)
8237 struct remote_state *rs = get_remote_state ();
8238 int max_size = get_memory_write_packet_size ();
8240 if (packet->support == PACKET_DISABLE)
8243 /* Insert header. */
8244 i = snprintf (rs->buf, max_size,
8245 "qXfer:%s:write:%s:%s:",
8246 object_name, annex ? annex : "",
8247 phex_nz (offset, sizeof offset));
8248 max_size -= (i + 1);
8250 /* Escape as much data as fits into rs->buf. */
8251 buf_len = remote_escape_output
8252 (writebuf, len, (rs->buf + i), &max_size, max_size);
8254 if (putpkt_binary (rs->buf, i + buf_len) < 0
8255 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8256 || packet_ok (rs->buf, packet) != PACKET_OK)
8259 unpack_varlen_hex (rs->buf, &n);
8263 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8264 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8265 number of bytes read is returned, or 0 for EOF, or -1 for error.
8266 The number of bytes read may be less than LEN without indicating an
8267 EOF. PACKET is checked and updated to indicate whether the remote
8268 target supports this object. */
8271 remote_read_qxfer (struct target_ops *ops, const char *object_name,
8273 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8274 struct packet_config *packet)
8276 static char *finished_object;
8277 static char *finished_annex;
8278 static ULONGEST finished_offset;
8280 struct remote_state *rs = get_remote_state ();
8281 LONGEST i, n, packet_len;
8283 if (packet->support == PACKET_DISABLE)
8286 /* Check whether we've cached an end-of-object packet that matches
8288 if (finished_object)
8290 if (strcmp (object_name, finished_object) == 0
8291 && strcmp (annex ? annex : "", finished_annex) == 0
8292 && offset == finished_offset)
8295 /* Otherwise, we're now reading something different. Discard
8297 xfree (finished_object);
8298 xfree (finished_annex);
8299 finished_object = NULL;
8300 finished_annex = NULL;
8303 /* Request only enough to fit in a single packet. The actual data
8304 may not, since we don't know how much of it will need to be escaped;
8305 the target is free to respond with slightly less data. We subtract
8306 five to account for the response type and the protocol frame. */
8307 n = min (get_remote_packet_size () - 5, len);
8308 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8309 object_name, annex ? annex : "",
8310 phex_nz (offset, sizeof offset),
8311 phex_nz (n, sizeof n));
8312 i = putpkt (rs->buf);
8317 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8318 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8321 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8322 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8324 /* 'm' means there is (or at least might be) more data after this
8325 batch. That does not make sense unless there's at least one byte
8326 of data in this reply. */
8327 if (rs->buf[0] == 'm' && packet_len == 1)
8328 error (_("Remote qXfer reply contained no data."));
8330 /* Got some data. */
8331 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
8333 /* 'l' is an EOF marker, possibly including a final block of data,
8334 or possibly empty. If we have the final block of a non-empty
8335 object, record this fact to bypass a subsequent partial read. */
8336 if (rs->buf[0] == 'l' && offset + i > 0)
8338 finished_object = xstrdup (object_name);
8339 finished_annex = xstrdup (annex ? annex : "");
8340 finished_offset = offset + i;
8347 remote_xfer_partial (struct target_ops *ops, enum target_object object,
8348 const char *annex, gdb_byte *readbuf,
8349 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
8351 struct remote_state *rs;
8356 set_remote_traceframe ();
8357 set_general_thread (inferior_ptid);
8359 rs = get_remote_state ();
8361 /* Handle memory using the standard memory routines. */
8362 if (object == TARGET_OBJECT_MEMORY)
8368 /* If the remote target is connected but not running, we should
8369 pass this request down to a lower stratum (e.g. the executable
8371 if (!target_has_execution)
8374 if (writebuf != NULL)
8375 xfered = remote_write_bytes (offset, writebuf, len);
8377 xfered = remote_read_bytes (offset, readbuf, len);
8381 else if (xfered == 0 && errno == 0)
8387 /* Handle SPU memory using qxfer packets. */
8388 if (object == TARGET_OBJECT_SPU)
8391 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8392 &remote_protocol_packets
8393 [PACKET_qXfer_spu_read]);
8395 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8396 &remote_protocol_packets
8397 [PACKET_qXfer_spu_write]);
8400 /* Handle extra signal info using qxfer packets. */
8401 if (object == TARGET_OBJECT_SIGNAL_INFO)
8404 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8405 &remote_protocol_packets
8406 [PACKET_qXfer_siginfo_read]);
8408 return remote_write_qxfer (ops, "siginfo", annex,
8409 writebuf, offset, len,
8410 &remote_protocol_packets
8411 [PACKET_qXfer_siginfo_write]);
8414 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8417 return remote_read_qxfer (ops, "statictrace", annex,
8418 readbuf, offset, len,
8419 &remote_protocol_packets
8420 [PACKET_qXfer_statictrace_read]);
8425 /* Only handle flash writes. */
8426 if (writebuf != NULL)
8432 case TARGET_OBJECT_FLASH:
8433 xfered = remote_flash_write (ops, offset, len, writebuf);
8437 else if (xfered == 0 && errno == 0)
8447 /* Map pre-existing objects onto letters. DO NOT do this for new
8448 objects!!! Instead specify new query packets. */
8451 case TARGET_OBJECT_AVR:
8455 case TARGET_OBJECT_AUXV:
8456 gdb_assert (annex == NULL);
8457 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8458 &remote_protocol_packets[PACKET_qXfer_auxv]);
8460 case TARGET_OBJECT_AVAILABLE_FEATURES:
8461 return remote_read_qxfer
8462 (ops, "features", annex, readbuf, offset, len,
8463 &remote_protocol_packets[PACKET_qXfer_features]);
8465 case TARGET_OBJECT_LIBRARIES:
8466 return remote_read_qxfer
8467 (ops, "libraries", annex, readbuf, offset, len,
8468 &remote_protocol_packets[PACKET_qXfer_libraries]);
8470 case TARGET_OBJECT_LIBRARIES_SVR4:
8471 return remote_read_qxfer
8472 (ops, "libraries-svr4", annex, readbuf, offset, len,
8473 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8475 case TARGET_OBJECT_MEMORY_MAP:
8476 gdb_assert (annex == NULL);
8477 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
8478 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8480 case TARGET_OBJECT_OSDATA:
8481 /* Should only get here if we're connected. */
8482 gdb_assert (remote_desc);
8483 return remote_read_qxfer
8484 (ops, "osdata", annex, readbuf, offset, len,
8485 &remote_protocol_packets[PACKET_qXfer_osdata]);
8487 case TARGET_OBJECT_THREADS:
8488 gdb_assert (annex == NULL);
8489 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
8490 &remote_protocol_packets[PACKET_qXfer_threads]);
8492 case TARGET_OBJECT_TRACEFRAME_INFO:
8493 gdb_assert (annex == NULL);
8494 return remote_read_qxfer
8495 (ops, "traceframe-info", annex, readbuf, offset, len,
8496 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
8498 case TARGET_OBJECT_FDPIC:
8499 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
8500 &remote_protocol_packets[PACKET_qXfer_fdpic]);
8505 /* Note: a zero OFFSET and LEN can be used to query the minimum
8507 if (offset == 0 && len == 0)
8508 return (get_remote_packet_size ());
8509 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
8510 large enough let the caller deal with it. */
8511 if (len < get_remote_packet_size ())
8513 len = get_remote_packet_size ();
8515 /* Except for querying the minimum buffer size, target must be open. */
8517 error (_("remote query is only available after target open"));
8519 gdb_assert (annex != NULL);
8520 gdb_assert (readbuf != NULL);
8526 /* We used one buffer char for the remote protocol q command and
8527 another for the query type. As the remote protocol encapsulation
8528 uses 4 chars plus one extra in case we are debugging
8529 (remote_debug), we have PBUFZIZ - 7 left to pack the query
8532 while (annex[i] && (i < (get_remote_packet_size () - 8)))
8534 /* Bad caller may have sent forbidden characters. */
8535 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
8540 gdb_assert (annex[i] == '\0');
8542 i = putpkt (rs->buf);
8546 getpkt (&rs->buf, &rs->buf_size, 0);
8547 strcpy ((char *) readbuf, rs->buf);
8549 return strlen ((char *) readbuf);
8553 remote_search_memory (struct target_ops* ops,
8554 CORE_ADDR start_addr, ULONGEST search_space_len,
8555 const gdb_byte *pattern, ULONGEST pattern_len,
8556 CORE_ADDR *found_addrp)
8558 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
8559 struct remote_state *rs = get_remote_state ();
8560 int max_size = get_memory_write_packet_size ();
8561 struct packet_config *packet =
8562 &remote_protocol_packets[PACKET_qSearch_memory];
8563 /* Number of packet bytes used to encode the pattern;
8564 this could be more than PATTERN_LEN due to escape characters. */
8565 int escaped_pattern_len;
8566 /* Amount of pattern that was encodable in the packet. */
8567 int used_pattern_len;
8570 ULONGEST found_addr;
8572 /* Don't go to the target if we don't have to.
8573 This is done before checking packet->support to avoid the possibility that
8574 a success for this edge case means the facility works in general. */
8575 if (pattern_len > search_space_len)
8577 if (pattern_len == 0)
8579 *found_addrp = start_addr;
8583 /* If we already know the packet isn't supported, fall back to the simple
8584 way of searching memory. */
8586 if (packet->support == PACKET_DISABLE)
8588 /* Target doesn't provided special support, fall back and use the
8589 standard support (copy memory and do the search here). */
8590 return simple_search_memory (ops, start_addr, search_space_len,
8591 pattern, pattern_len, found_addrp);
8594 /* Insert header. */
8595 i = snprintf (rs->buf, max_size,
8596 "qSearch:memory:%s;%s;",
8597 phex_nz (start_addr, addr_size),
8598 phex_nz (search_space_len, sizeof (search_space_len)));
8599 max_size -= (i + 1);
8601 /* Escape as much data as fits into rs->buf. */
8602 escaped_pattern_len =
8603 remote_escape_output (pattern, pattern_len, (rs->buf + i),
8604 &used_pattern_len, max_size);
8606 /* Bail if the pattern is too large. */
8607 if (used_pattern_len != pattern_len)
8608 error (_("Pattern is too large to transmit to remote target."));
8610 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
8611 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8612 || packet_ok (rs->buf, packet) != PACKET_OK)
8614 /* The request may not have worked because the command is not
8615 supported. If so, fall back to the simple way. */
8616 if (packet->support == PACKET_DISABLE)
8618 return simple_search_memory (ops, start_addr, search_space_len,
8619 pattern, pattern_len, found_addrp);
8624 if (rs->buf[0] == '0')
8626 else if (rs->buf[0] == '1')
8629 if (rs->buf[1] != ',')
8630 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
8631 unpack_varlen_hex (rs->buf + 2, &found_addr);
8632 *found_addrp = found_addr;
8635 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
8641 remote_rcmd (char *command,
8642 struct ui_file *outbuf)
8644 struct remote_state *rs = get_remote_state ();
8648 error (_("remote rcmd is only available after target open"));
8650 /* Send a NULL command across as an empty command. */
8651 if (command == NULL)
8654 /* The query prefix. */
8655 strcpy (rs->buf, "qRcmd,");
8656 p = strchr (rs->buf, '\0');
8658 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
8659 > get_remote_packet_size ())
8660 error (_("\"monitor\" command ``%s'' is too long."), command);
8662 /* Encode the actual command. */
8663 bin2hex ((gdb_byte *) command, p, 0);
8665 if (putpkt (rs->buf) < 0)
8666 error (_("Communication problem with target."));
8668 /* get/display the response */
8673 /* XXX - see also remote_get_noisy_reply(). */
8674 QUIT; /* Allow user to bail out with ^C. */
8676 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
8678 /* Timeout. Continue to (try to) read responses.
8679 This is better than stopping with an error, assuming the stub
8680 is still executing the (long) monitor command.
8681 If needed, the user can interrupt gdb using C-c, obtaining
8682 an effect similar to stop on timeout. */
8687 error (_("Target does not support this command."));
8688 if (buf[0] == 'O' && buf[1] != 'K')
8690 remote_console_output (buf + 1); /* 'O' message from stub. */
8693 if (strcmp (buf, "OK") == 0)
8695 if (strlen (buf) == 3 && buf[0] == 'E'
8696 && isdigit (buf[1]) && isdigit (buf[2]))
8698 error (_("Protocol error with Rcmd"));
8700 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
8702 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
8704 fputc_unfiltered (c, outbuf);
8710 static VEC(mem_region_s) *
8711 remote_memory_map (struct target_ops *ops)
8713 VEC(mem_region_s) *result = NULL;
8714 char *text = target_read_stralloc (¤t_target,
8715 TARGET_OBJECT_MEMORY_MAP, NULL);
8719 struct cleanup *back_to = make_cleanup (xfree, text);
8721 result = parse_memory_map (text);
8722 do_cleanups (back_to);
8729 packet_command (char *args, int from_tty)
8731 struct remote_state *rs = get_remote_state ();
8734 error (_("command can only be used with remote target"));
8737 error (_("remote-packet command requires packet text as argument"));
8739 puts_filtered ("sending: ");
8740 print_packet (args);
8741 puts_filtered ("\n");
8744 getpkt (&rs->buf, &rs->buf_size, 0);
8745 puts_filtered ("received: ");
8746 print_packet (rs->buf);
8747 puts_filtered ("\n");
8751 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
8753 static void display_thread_info (struct gdb_ext_thread_info *info);
8755 static void threadset_test_cmd (char *cmd, int tty);
8757 static void threadalive_test (char *cmd, int tty);
8759 static void threadlist_test_cmd (char *cmd, int tty);
8761 int get_and_display_threadinfo (threadref *ref);
8763 static void threadinfo_test_cmd (char *cmd, int tty);
8765 static int thread_display_step (threadref *ref, void *context);
8767 static void threadlist_update_test_cmd (char *cmd, int tty);
8769 static void init_remote_threadtests (void);
8771 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
8774 threadset_test_cmd (char *cmd, int tty)
8776 int sample_thread = SAMPLE_THREAD;
8778 printf_filtered (_("Remote threadset test\n"));
8779 set_general_thread (sample_thread);
8784 threadalive_test (char *cmd, int tty)
8786 int sample_thread = SAMPLE_THREAD;
8787 int pid = ptid_get_pid (inferior_ptid);
8788 ptid_t ptid = ptid_build (pid, 0, sample_thread);
8790 if (remote_thread_alive (ptid))
8791 printf_filtered ("PASS: Thread alive test\n");
8793 printf_filtered ("FAIL: Thread alive test\n");
8796 void output_threadid (char *title, threadref *ref);
8799 output_threadid (char *title, threadref *ref)
8803 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
8805 printf_filtered ("%s %s\n", title, (&hexid[0]));
8809 threadlist_test_cmd (char *cmd, int tty)
8812 threadref nextthread;
8813 int done, result_count;
8814 threadref threadlist[3];
8816 printf_filtered ("Remote Threadlist test\n");
8817 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
8818 &result_count, &threadlist[0]))
8819 printf_filtered ("FAIL: threadlist test\n");
8822 threadref *scan = threadlist;
8823 threadref *limit = scan + result_count;
8825 while (scan < limit)
8826 output_threadid (" thread ", scan++);
8831 display_thread_info (struct gdb_ext_thread_info *info)
8833 output_threadid ("Threadid: ", &info->threadid);
8834 printf_filtered ("Name: %s\n ", info->shortname);
8835 printf_filtered ("State: %s\n", info->display);
8836 printf_filtered ("other: %s\n\n", info->more_display);
8840 get_and_display_threadinfo (threadref *ref)
8844 struct gdb_ext_thread_info threadinfo;
8846 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
8847 | TAG_MOREDISPLAY | TAG_DISPLAY;
8848 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
8849 display_thread_info (&threadinfo);
8854 threadinfo_test_cmd (char *cmd, int tty)
8856 int athread = SAMPLE_THREAD;
8860 int_to_threadref (&thread, athread);
8861 printf_filtered ("Remote Threadinfo test\n");
8862 if (!get_and_display_threadinfo (&thread))
8863 printf_filtered ("FAIL cannot get thread info\n");
8867 thread_display_step (threadref *ref, void *context)
8869 /* output_threadid(" threadstep ",ref); *//* simple test */
8870 return get_and_display_threadinfo (ref);
8874 threadlist_update_test_cmd (char *cmd, int tty)
8876 printf_filtered ("Remote Threadlist update test\n");
8877 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
8881 init_remote_threadtests (void)
8883 add_com ("tlist", class_obscure, threadlist_test_cmd,
8884 _("Fetch and print the remote list of "
8885 "thread identifiers, one pkt only"));
8886 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
8887 _("Fetch and display info about one thread"));
8888 add_com ("tset", class_obscure, threadset_test_cmd,
8889 _("Test setting to a different thread"));
8890 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
8891 _("Iterate through updating all remote thread info"));
8892 add_com ("talive", class_obscure, threadalive_test,
8893 _(" Remote thread alive test "));
8898 /* Convert a thread ID to a string. Returns the string in a static
8902 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
8904 static char buf[64];
8905 struct remote_state *rs = get_remote_state ();
8907 if (ptid_equal (ptid, null_ptid))
8908 return normal_pid_to_str (ptid);
8909 else if (ptid_is_pid (ptid))
8911 /* Printing an inferior target id. */
8913 /* When multi-process extensions are off, there's no way in the
8914 remote protocol to know the remote process id, if there's any
8915 at all. There's one exception --- when we're connected with
8916 target extended-remote, and we manually attached to a process
8917 with "attach PID". We don't record anywhere a flag that
8918 allows us to distinguish that case from the case of
8919 connecting with extended-remote and the stub already being
8920 attached to a process, and reporting yes to qAttached, hence
8921 no smart special casing here. */
8922 if (!remote_multi_process_p (rs))
8924 xsnprintf (buf, sizeof buf, "Remote target");
8928 return normal_pid_to_str (ptid);
8932 if (ptid_equal (magic_null_ptid, ptid))
8933 xsnprintf (buf, sizeof buf, "Thread <main>");
8934 else if (rs->extended && remote_multi_process_p (rs))
8935 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
8936 ptid_get_pid (ptid), ptid_get_tid (ptid));
8938 xsnprintf (buf, sizeof buf, "Thread %ld",
8939 ptid_get_tid (ptid));
8944 /* Get the address of the thread local variable in OBJFILE which is
8945 stored at OFFSET within the thread local storage for thread PTID. */
8948 remote_get_thread_local_address (struct target_ops *ops,
8949 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
8951 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
8953 struct remote_state *rs = get_remote_state ();
8955 char *endp = rs->buf + get_remote_packet_size ();
8956 enum packet_result result;
8958 strcpy (p, "qGetTLSAddr:");
8960 p = write_ptid (p, endp, ptid);
8962 p += hexnumstr (p, offset);
8964 p += hexnumstr (p, lm);
8968 getpkt (&rs->buf, &rs->buf_size, 0);
8969 result = packet_ok (rs->buf,
8970 &remote_protocol_packets[PACKET_qGetTLSAddr]);
8971 if (result == PACKET_OK)
8975 unpack_varlen_hex (rs->buf, &result);
8978 else if (result == PACKET_UNKNOWN)
8979 throw_error (TLS_GENERIC_ERROR,
8980 _("Remote target doesn't support qGetTLSAddr packet"));
8982 throw_error (TLS_GENERIC_ERROR,
8983 _("Remote target failed to process qGetTLSAddr request"));
8986 throw_error (TLS_GENERIC_ERROR,
8987 _("TLS not supported or disabled on this target"));
8992 /* Provide thread local base, i.e. Thread Information Block address.
8993 Returns 1 if ptid is found and thread_local_base is non zero. */
8996 remote_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
8998 if (remote_protocol_packets[PACKET_qGetTIBAddr].support != PACKET_DISABLE)
9000 struct remote_state *rs = get_remote_state ();
9002 char *endp = rs->buf + get_remote_packet_size ();
9003 enum packet_result result;
9005 strcpy (p, "qGetTIBAddr:");
9007 p = write_ptid (p, endp, ptid);
9011 getpkt (&rs->buf, &rs->buf_size, 0);
9012 result = packet_ok (rs->buf,
9013 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9014 if (result == PACKET_OK)
9018 unpack_varlen_hex (rs->buf, &result);
9020 *addr = (CORE_ADDR) result;
9023 else if (result == PACKET_UNKNOWN)
9024 error (_("Remote target doesn't support qGetTIBAddr packet"));
9026 error (_("Remote target failed to process qGetTIBAddr request"));
9029 error (_("qGetTIBAddr not supported or disabled on this target"));
9034 /* Support for inferring a target description based on the current
9035 architecture and the size of a 'g' packet. While the 'g' packet
9036 can have any size (since optional registers can be left off the
9037 end), some sizes are easily recognizable given knowledge of the
9038 approximate architecture. */
9040 struct remote_g_packet_guess
9043 const struct target_desc *tdesc;
9045 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9046 DEF_VEC_O(remote_g_packet_guess_s);
9048 struct remote_g_packet_data
9050 VEC(remote_g_packet_guess_s) *guesses;
9053 static struct gdbarch_data *remote_g_packet_data_handle;
9056 remote_g_packet_data_init (struct obstack *obstack)
9058 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9062 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9063 const struct target_desc *tdesc)
9065 struct remote_g_packet_data *data
9066 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9067 struct remote_g_packet_guess new_guess, *guess;
9070 gdb_assert (tdesc != NULL);
9073 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9075 if (guess->bytes == bytes)
9076 internal_error (__FILE__, __LINE__,
9077 _("Duplicate g packet description added for size %d"),
9080 new_guess.bytes = bytes;
9081 new_guess.tdesc = tdesc;
9082 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9085 /* Return 1 if remote_read_description would do anything on this target
9086 and architecture, 0 otherwise. */
9089 remote_read_description_p (struct target_ops *target)
9091 struct remote_g_packet_data *data
9092 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
9094 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9100 static const struct target_desc *
9101 remote_read_description (struct target_ops *target)
9103 struct remote_g_packet_data *data
9104 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
9106 /* Do not try this during initial connection, when we do not know
9107 whether there is a running but stopped thread. */
9108 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9111 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9113 struct remote_g_packet_guess *guess;
9115 int bytes = send_g_packet ();
9118 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9120 if (guess->bytes == bytes)
9121 return guess->tdesc;
9123 /* We discard the g packet. A minor optimization would be to
9124 hold on to it, and fill the register cache once we have selected
9125 an architecture, but it's too tricky to do safely. */
9131 /* Remote file transfer support. This is host-initiated I/O, not
9132 target-initiated; for target-initiated, see remote-fileio.c. */
9134 /* If *LEFT is at least the length of STRING, copy STRING to
9135 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9136 decrease *LEFT. Otherwise raise an error. */
9139 remote_buffer_add_string (char **buffer, int *left, char *string)
9141 int len = strlen (string);
9144 error (_("Packet too long for target."));
9146 memcpy (*buffer, string, len);
9150 /* NUL-terminate the buffer as a convenience, if there is
9156 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9157 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9158 decrease *LEFT. Otherwise raise an error. */
9161 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9164 if (2 * len > *left)
9165 error (_("Packet too long for target."));
9167 bin2hex (bytes, *buffer, len);
9171 /* NUL-terminate the buffer as a convenience, if there is
9177 /* If *LEFT is large enough, convert VALUE to hex and add it to
9178 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9179 decrease *LEFT. Otherwise raise an error. */
9182 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9184 int len = hexnumlen (value);
9187 error (_("Packet too long for target."));
9189 hexnumstr (*buffer, value);
9193 /* NUL-terminate the buffer as a convenience, if there is
9199 /* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9200 value, *REMOTE_ERRNO to the remote error number or zero if none
9201 was included, and *ATTACHMENT to point to the start of the annex
9202 if any. The length of the packet isn't needed here; there may
9203 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9205 Return 0 if the packet could be parsed, -1 if it could not. If
9206 -1 is returned, the other variables may not be initialized. */
9209 remote_hostio_parse_result (char *buffer, int *retcode,
9210 int *remote_errno, char **attachment)
9217 if (buffer[0] != 'F')
9221 *retcode = strtol (&buffer[1], &p, 16);
9222 if (errno != 0 || p == &buffer[1])
9225 /* Check for ",errno". */
9229 *remote_errno = strtol (p + 1, &p2, 16);
9230 if (errno != 0 || p + 1 == p2)
9235 /* Check for ";attachment". If there is no attachment, the
9236 packet should end here. */
9239 *attachment = p + 1;
9242 else if (*p == '\0')
9248 /* Send a prepared I/O packet to the target and read its response.
9249 The prepared packet is in the global RS->BUF before this function
9250 is called, and the answer is there when we return.
9252 COMMAND_BYTES is the length of the request to send, which may include
9253 binary data. WHICH_PACKET is the packet configuration to check
9254 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9255 is set to the error number and -1 is returned. Otherwise the value
9256 returned by the function is returned.
9258 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9259 attachment is expected; an error will be reported if there's a
9260 mismatch. If one is found, *ATTACHMENT will be set to point into
9261 the packet buffer and *ATTACHMENT_LEN will be set to the
9262 attachment's length. */
9265 remote_hostio_send_command (int command_bytes, int which_packet,
9266 int *remote_errno, char **attachment,
9267 int *attachment_len)
9269 struct remote_state *rs = get_remote_state ();
9270 int ret, bytes_read;
9271 char *attachment_tmp;
9274 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
9276 *remote_errno = FILEIO_ENOSYS;
9280 putpkt_binary (rs->buf, command_bytes);
9281 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9283 /* If it timed out, something is wrong. Don't try to parse the
9287 *remote_errno = FILEIO_EINVAL;
9291 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9294 *remote_errno = FILEIO_EINVAL;
9296 case PACKET_UNKNOWN:
9297 *remote_errno = FILEIO_ENOSYS;
9303 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9306 *remote_errno = FILEIO_EINVAL;
9310 /* Make sure we saw an attachment if and only if we expected one. */
9311 if ((attachment_tmp == NULL && attachment != NULL)
9312 || (attachment_tmp != NULL && attachment == NULL))
9314 *remote_errno = FILEIO_EINVAL;
9318 /* If an attachment was found, it must point into the packet buffer;
9319 work out how many bytes there were. */
9320 if (attachment_tmp != NULL)
9322 *attachment = attachment_tmp;
9323 *attachment_len = bytes_read - (*attachment - rs->buf);
9329 /* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9330 remote file descriptor, or -1 if an error occurs (and set
9334 remote_hostio_open (const char *filename, int flags, int mode,
9337 struct remote_state *rs = get_remote_state ();
9339 int left = get_remote_packet_size () - 1;
9341 remote_buffer_add_string (&p, &left, "vFile:open:");
9343 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9345 remote_buffer_add_string (&p, &left, ",");
9347 remote_buffer_add_int (&p, &left, flags);
9348 remote_buffer_add_string (&p, &left, ",");
9350 remote_buffer_add_int (&p, &left, mode);
9352 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9353 remote_errno, NULL, NULL);
9356 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9357 Return the number of bytes written, or -1 if an error occurs (and
9358 set *REMOTE_ERRNO). */
9361 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
9362 ULONGEST offset, int *remote_errno)
9364 struct remote_state *rs = get_remote_state ();
9366 int left = get_remote_packet_size ();
9369 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9371 remote_buffer_add_int (&p, &left, fd);
9372 remote_buffer_add_string (&p, &left, ",");
9374 remote_buffer_add_int (&p, &left, offset);
9375 remote_buffer_add_string (&p, &left, ",");
9377 p += remote_escape_output (write_buf, len, p, &out_len,
9378 get_remote_packet_size () - (p - rs->buf));
9380 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9381 remote_errno, NULL, NULL);
9384 /* Read up to LEN bytes FD on the remote target into READ_BUF
9385 Return the number of bytes read, or -1 if an error occurs (and
9386 set *REMOTE_ERRNO). */
9389 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
9390 ULONGEST offset, int *remote_errno)
9392 struct remote_state *rs = get_remote_state ();
9395 int left = get_remote_packet_size ();
9396 int ret, attachment_len;
9399 remote_buffer_add_string (&p, &left, "vFile:pread:");
9401 remote_buffer_add_int (&p, &left, fd);
9402 remote_buffer_add_string (&p, &left, ",");
9404 remote_buffer_add_int (&p, &left, len);
9405 remote_buffer_add_string (&p, &left, ",");
9407 remote_buffer_add_int (&p, &left, offset);
9409 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9410 remote_errno, &attachment,
9416 read_len = remote_unescape_input (attachment, attachment_len,
9418 if (read_len != ret)
9419 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9424 /* Close FD on the remote target. Return 0, or -1 if an error occurs
9425 (and set *REMOTE_ERRNO). */
9428 remote_hostio_close (int fd, int *remote_errno)
9430 struct remote_state *rs = get_remote_state ();
9432 int left = get_remote_packet_size () - 1;
9434 remote_buffer_add_string (&p, &left, "vFile:close:");
9436 remote_buffer_add_int (&p, &left, fd);
9438 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9439 remote_errno, NULL, NULL);
9442 /* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9443 occurs (and set *REMOTE_ERRNO). */
9446 remote_hostio_unlink (const char *filename, int *remote_errno)
9448 struct remote_state *rs = get_remote_state ();
9450 int left = get_remote_packet_size () - 1;
9452 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9454 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9457 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9458 remote_errno, NULL, NULL);
9461 /* Read value of symbolic link FILENAME on the remote target. Return
9462 a null-terminated string allocated via xmalloc, or NULL if an error
9463 occurs (and set *REMOTE_ERRNO). */
9466 remote_hostio_readlink (const char *filename, int *remote_errno)
9468 struct remote_state *rs = get_remote_state ();
9471 int left = get_remote_packet_size ();
9472 int len, attachment_len;
9476 remote_buffer_add_string (&p, &left, "vFile:readlink:");
9478 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9481 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
9482 remote_errno, &attachment,
9488 ret = xmalloc (len + 1);
9490 read_len = remote_unescape_input (attachment, attachment_len,
9492 if (read_len != len)
9493 error (_("Readlink returned %d, but %d bytes."), len, read_len);
9500 remote_fileio_errno_to_host (int errnum)
9524 case FILEIO_ENOTDIR:
9544 case FILEIO_ENAMETOOLONG:
9545 return ENAMETOOLONG;
9551 remote_hostio_error (int errnum)
9553 int host_error = remote_fileio_errno_to_host (errnum);
9555 if (host_error == -1)
9556 error (_("Unknown remote I/O error %d"), errnum);
9558 error (_("Remote I/O error: %s"), safe_strerror (host_error));
9562 remote_hostio_close_cleanup (void *opaque)
9564 int fd = *(int *) opaque;
9567 remote_hostio_close (fd, &remote_errno);
9572 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
9574 const char *filename = bfd_get_filename (abfd);
9575 int fd, remote_errno;
9578 gdb_assert (remote_filename_p (filename));
9580 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
9583 errno = remote_fileio_errno_to_host (remote_errno);
9584 bfd_set_error (bfd_error_system_call);
9588 stream = xmalloc (sizeof (int));
9594 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
9596 int fd = *(int *)stream;
9601 /* Ignore errors on close; these may happen if the remote
9602 connection was already torn down. */
9603 remote_hostio_close (fd, &remote_errno);
9609 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
9610 file_ptr nbytes, file_ptr offset)
9612 int fd = *(int *)stream;
9614 file_ptr pos, bytes;
9617 while (nbytes > pos)
9619 bytes = remote_hostio_pread (fd, (char *)buf + pos, nbytes - pos,
9620 offset + pos, &remote_errno);
9622 /* Success, but no bytes, means end-of-file. */
9626 errno = remote_fileio_errno_to_host (remote_errno);
9627 bfd_set_error (bfd_error_system_call);
9638 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
9640 /* FIXME: We should probably implement remote_hostio_stat. */
9641 sb->st_size = INT_MAX;
9646 remote_filename_p (const char *filename)
9648 return strncmp (filename, "remote:", 7) == 0;
9652 remote_bfd_open (const char *remote_file, const char *target)
9654 return bfd_openr_iovec (remote_file, target,
9655 remote_bfd_iovec_open, NULL,
9656 remote_bfd_iovec_pread,
9657 remote_bfd_iovec_close,
9658 remote_bfd_iovec_stat);
9662 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
9664 struct cleanup *back_to, *close_cleanup;
9665 int retcode, fd, remote_errno, bytes, io_size;
9668 int bytes_in_buffer;
9673 error (_("command can only be used with remote target"));
9675 file = fopen (local_file, "rb");
9677 perror_with_name (local_file);
9678 back_to = make_cleanup_fclose (file);
9680 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
9682 0700, &remote_errno);
9684 remote_hostio_error (remote_errno);
9686 /* Send up to this many bytes at once. They won't all fit in the
9687 remote packet limit, so we'll transfer slightly fewer. */
9688 io_size = get_remote_packet_size ();
9689 buffer = xmalloc (io_size);
9690 make_cleanup (xfree, buffer);
9692 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
9694 bytes_in_buffer = 0;
9697 while (bytes_in_buffer || !saw_eof)
9701 bytes = fread (buffer + bytes_in_buffer, 1,
9702 io_size - bytes_in_buffer,
9707 error (_("Error reading %s."), local_file);
9710 /* EOF. Unless there is something still in the
9711 buffer from the last iteration, we are done. */
9713 if (bytes_in_buffer == 0)
9721 bytes += bytes_in_buffer;
9722 bytes_in_buffer = 0;
9724 retcode = remote_hostio_pwrite (fd, buffer, bytes,
9725 offset, &remote_errno);
9728 remote_hostio_error (remote_errno);
9729 else if (retcode == 0)
9730 error (_("Remote write of %d bytes returned 0!"), bytes);
9731 else if (retcode < bytes)
9733 /* Short write. Save the rest of the read data for the next
9735 bytes_in_buffer = bytes - retcode;
9736 memmove (buffer, buffer + retcode, bytes_in_buffer);
9742 discard_cleanups (close_cleanup);
9743 if (remote_hostio_close (fd, &remote_errno))
9744 remote_hostio_error (remote_errno);
9747 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
9748 do_cleanups (back_to);
9752 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
9754 struct cleanup *back_to, *close_cleanup;
9755 int fd, remote_errno, bytes, io_size;
9761 error (_("command can only be used with remote target"));
9763 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
9765 remote_hostio_error (remote_errno);
9767 file = fopen (local_file, "wb");
9769 perror_with_name (local_file);
9770 back_to = make_cleanup_fclose (file);
9772 /* Send up to this many bytes at once. They won't all fit in the
9773 remote packet limit, so we'll transfer slightly fewer. */
9774 io_size = get_remote_packet_size ();
9775 buffer = xmalloc (io_size);
9776 make_cleanup (xfree, buffer);
9778 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
9783 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
9785 /* Success, but no bytes, means end-of-file. */
9788 remote_hostio_error (remote_errno);
9792 bytes = fwrite (buffer, 1, bytes, file);
9794 perror_with_name (local_file);
9797 discard_cleanups (close_cleanup);
9798 if (remote_hostio_close (fd, &remote_errno))
9799 remote_hostio_error (remote_errno);
9802 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
9803 do_cleanups (back_to);
9807 remote_file_delete (const char *remote_file, int from_tty)
9809 int retcode, remote_errno;
9812 error (_("command can only be used with remote target"));
9814 retcode = remote_hostio_unlink (remote_file, &remote_errno);
9816 remote_hostio_error (remote_errno);
9819 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
9823 remote_put_command (char *args, int from_tty)
9825 struct cleanup *back_to;
9829 error_no_arg (_("file to put"));
9831 argv = gdb_buildargv (args);
9832 back_to = make_cleanup_freeargv (argv);
9833 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
9834 error (_("Invalid parameters to remote put"));
9836 remote_file_put (argv[0], argv[1], from_tty);
9838 do_cleanups (back_to);
9842 remote_get_command (char *args, int from_tty)
9844 struct cleanup *back_to;
9848 error_no_arg (_("file to get"));
9850 argv = gdb_buildargv (args);
9851 back_to = make_cleanup_freeargv (argv);
9852 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
9853 error (_("Invalid parameters to remote get"));
9855 remote_file_get (argv[0], argv[1], from_tty);
9857 do_cleanups (back_to);
9861 remote_delete_command (char *args, int from_tty)
9863 struct cleanup *back_to;
9867 error_no_arg (_("file to delete"));
9869 argv = gdb_buildargv (args);
9870 back_to = make_cleanup_freeargv (argv);
9871 if (argv[0] == NULL || argv[1] != NULL)
9872 error (_("Invalid parameters to remote delete"));
9874 remote_file_delete (argv[0], from_tty);
9876 do_cleanups (back_to);
9880 remote_command (char *args, int from_tty)
9882 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
9886 remote_can_execute_reverse (void)
9888 if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
9889 || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
9896 remote_supports_non_stop (void)
9902 remote_supports_disable_randomization (void)
9904 /* Only supported in extended mode. */
9909 remote_supports_multi_process (void)
9911 struct remote_state *rs = get_remote_state ();
9913 /* Only extended-remote handles being attached to multiple
9914 processes, even though plain remote can use the multi-process
9915 thread id extensions, so that GDB knows the target process's
9917 return rs->extended && remote_multi_process_p (rs);
9921 remote_supports_cond_tracepoints (void)
9923 struct remote_state *rs = get_remote_state ();
9925 return rs->cond_tracepoints;
9929 remote_supports_cond_breakpoints (void)
9931 struct remote_state *rs = get_remote_state ();
9933 return rs->cond_breakpoints;
9937 remote_supports_fast_tracepoints (void)
9939 struct remote_state *rs = get_remote_state ();
9941 return rs->fast_tracepoints;
9945 remote_supports_static_tracepoints (void)
9947 struct remote_state *rs = get_remote_state ();
9949 return rs->static_tracepoints;
9953 remote_supports_install_in_trace (void)
9955 struct remote_state *rs = get_remote_state ();
9957 return rs->install_in_trace;
9961 remote_supports_enable_disable_tracepoint (void)
9963 struct remote_state *rs = get_remote_state ();
9965 return rs->enable_disable_tracepoints;
9969 remote_supports_string_tracing (void)
9971 struct remote_state *rs = get_remote_state ();
9973 return rs->string_tracing;
9977 remote_trace_init (void)
9980 remote_get_noisy_reply (&target_buf, &target_buf_size);
9981 if (strcmp (target_buf, "OK") != 0)
9982 error (_("Target does not support this command."));
9985 static void free_actions_list (char **actions_list);
9986 static void free_actions_list_cleanup_wrapper (void *);
9988 free_actions_list_cleanup_wrapper (void *al)
9990 free_actions_list (al);
9994 free_actions_list (char **actions_list)
9998 if (actions_list == 0)
10001 for (ndx = 0; actions_list[ndx]; ndx++)
10002 xfree (actions_list[ndx]);
10004 xfree (actions_list);
10007 /* Recursive routine to walk through command list including loops, and
10008 download packets for each command. */
10011 remote_download_command_source (int num, ULONGEST addr,
10012 struct command_line *cmds)
10014 struct remote_state *rs = get_remote_state ();
10015 struct command_line *cmd;
10017 for (cmd = cmds; cmd; cmd = cmd->next)
10019 QUIT; /* Allow user to bail out with ^C. */
10020 strcpy (rs->buf, "QTDPsrc:");
10021 encode_source_string (num, addr, "cmd", cmd->line,
10022 rs->buf + strlen (rs->buf),
10023 rs->buf_size - strlen (rs->buf));
10025 remote_get_noisy_reply (&target_buf, &target_buf_size);
10026 if (strcmp (target_buf, "OK"))
10027 warning (_("Target does not support source download."));
10029 if (cmd->control_type == while_control
10030 || cmd->control_type == while_stepping_control)
10032 remote_download_command_source (num, addr, *cmd->body_list);
10034 QUIT; /* Allow user to bail out with ^C. */
10035 strcpy (rs->buf, "QTDPsrc:");
10036 encode_source_string (num, addr, "cmd", "end",
10037 rs->buf + strlen (rs->buf),
10038 rs->buf_size - strlen (rs->buf));
10040 remote_get_noisy_reply (&target_buf, &target_buf_size);
10041 if (strcmp (target_buf, "OK"))
10042 warning (_("Target does not support source download."));
10048 remote_download_tracepoint (struct bp_location *loc)
10054 char **tdp_actions;
10055 char **stepping_actions;
10057 struct cleanup *old_chain = NULL;
10058 struct agent_expr *aexpr;
10059 struct cleanup *aexpr_chain = NULL;
10061 struct breakpoint *b = loc->owner;
10062 struct tracepoint *t = (struct tracepoint *) b;
10064 encode_actions (loc->owner, loc, &tdp_actions, &stepping_actions);
10065 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10067 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10070 tpaddr = loc->address;
10071 sprintf_vma (addrbuf, tpaddr);
10072 sprintf (buf, "QTDP:%x:%s:%c:%lx:%x", b->number,
10073 addrbuf, /* address */
10074 (b->enable_state == bp_enabled ? 'E' : 'D'),
10075 t->step_count, t->pass_count);
10076 /* Fast tracepoints are mostly handled by the target, but we can
10077 tell the target how big of an instruction block should be moved
10079 if (b->type == bp_fast_tracepoint)
10081 /* Only test for support at download time; we may not know
10082 target capabilities at definition time. */
10083 if (remote_supports_fast_tracepoints ())
10087 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch,
10088 tpaddr, &isize, NULL))
10089 sprintf (buf + strlen (buf), ":F%x", isize);
10091 /* If it passed validation at definition but fails now,
10092 something is very wrong. */
10093 internal_error (__FILE__, __LINE__,
10094 _("Fast tracepoint not "
10095 "valid during download"));
10098 /* Fast tracepoints are functionally identical to regular
10099 tracepoints, so don't take lack of support as a reason to
10100 give up on the trace run. */
10101 warning (_("Target does not support fast tracepoints, "
10102 "downloading %d as regular tracepoint"), b->number);
10104 else if (b->type == bp_static_tracepoint)
10106 /* Only test for support at download time; we may not know
10107 target capabilities at definition time. */
10108 if (remote_supports_static_tracepoints ())
10110 struct static_tracepoint_marker marker;
10112 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10113 strcat (buf, ":S");
10115 error (_("Static tracepoint not valid during download"));
10118 /* Fast tracepoints are functionally identical to regular
10119 tracepoints, so don't take lack of support as a reason
10120 to give up on the trace run. */
10121 error (_("Target does not support static tracepoints"));
10123 /* If the tracepoint has a conditional, make it into an agent
10124 expression and append to the definition. */
10127 /* Only test support at download time, we may not know target
10128 capabilities at definition time. */
10129 if (remote_supports_cond_tracepoints ())
10131 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10132 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
10133 sprintf (buf + strlen (buf), ":X%x,", aexpr->len);
10134 pkt = buf + strlen (buf);
10135 for (ndx = 0; ndx < aexpr->len; ++ndx)
10136 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10138 do_cleanups (aexpr_chain);
10141 warning (_("Target does not support conditional tracepoints, "
10142 "ignoring tp %d cond"), b->number);
10145 if (b->commands || *default_collect)
10148 remote_get_noisy_reply (&target_buf, &target_buf_size);
10149 if (strcmp (target_buf, "OK"))
10150 error (_("Target does not support tracepoints."));
10152 /* do_single_steps (t); */
10155 for (ndx = 0; tdp_actions[ndx]; ndx++)
10157 QUIT; /* Allow user to bail out with ^C. */
10158 sprintf (buf, "QTDP:-%x:%s:%s%c",
10159 b->number, addrbuf, /* address */
10161 ((tdp_actions[ndx + 1] || stepping_actions)
10164 remote_get_noisy_reply (&target_buf,
10166 if (strcmp (target_buf, "OK"))
10167 error (_("Error on target while setting tracepoints."));
10170 if (stepping_actions)
10172 for (ndx = 0; stepping_actions[ndx]; ndx++)
10174 QUIT; /* Allow user to bail out with ^C. */
10175 sprintf (buf, "QTDP:-%x:%s:%s%s%s",
10176 b->number, addrbuf, /* address */
10177 ((ndx == 0) ? "S" : ""),
10178 stepping_actions[ndx],
10179 (stepping_actions[ndx + 1] ? "-" : ""));
10181 remote_get_noisy_reply (&target_buf,
10183 if (strcmp (target_buf, "OK"))
10184 error (_("Error on target while setting tracepoints."));
10188 if (remote_protocol_packets[PACKET_TracepointSource].support
10191 if (b->addr_string)
10193 strcpy (buf, "QTDPsrc:");
10194 encode_source_string (b->number, loc->address,
10195 "at", b->addr_string, buf + strlen (buf),
10196 2048 - strlen (buf));
10199 remote_get_noisy_reply (&target_buf, &target_buf_size);
10200 if (strcmp (target_buf, "OK"))
10201 warning (_("Target does not support source download."));
10203 if (b->cond_string)
10205 strcpy (buf, "QTDPsrc:");
10206 encode_source_string (b->number, loc->address,
10207 "cond", b->cond_string, buf + strlen (buf),
10208 2048 - strlen (buf));
10210 remote_get_noisy_reply (&target_buf, &target_buf_size);
10211 if (strcmp (target_buf, "OK"))
10212 warning (_("Target does not support source download."));
10214 remote_download_command_source (b->number, loc->address,
10215 breakpoint_commands (b));
10218 do_cleanups (old_chain);
10222 remote_can_download_tracepoint (void)
10224 struct trace_status *ts = current_trace_status ();
10225 int status = remote_get_trace_status (ts);
10227 if (status == -1 || !ts->running_known || !ts->running)
10230 /* If we are in a tracing experiment, but remote stub doesn't support
10231 installing tracepoint in trace, we have to return. */
10232 if (!remote_supports_install_in_trace ())
10240 remote_download_trace_state_variable (struct trace_state_variable *tsv)
10242 struct remote_state *rs = get_remote_state ();
10245 sprintf (rs->buf, "QTDV:%x:%s:%x:",
10246 tsv->number, phex ((ULONGEST) tsv->initial_value, 8), tsv->builtin);
10247 p = rs->buf + strlen (rs->buf);
10248 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10249 error (_("Trace state variable name too long for tsv definition packet"));
10250 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, 0);
10253 remote_get_noisy_reply (&target_buf, &target_buf_size);
10254 if (*target_buf == '\0')
10255 error (_("Target does not support this command."));
10256 if (strcmp (target_buf, "OK") != 0)
10257 error (_("Error on target while downloading trace state variable."));
10261 remote_enable_tracepoint (struct bp_location *location)
10263 struct remote_state *rs = get_remote_state ();
10266 sprintf_vma (addr_buf, location->address);
10267 sprintf (rs->buf, "QTEnable:%x:%s", location->owner->number, addr_buf);
10269 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10270 if (*rs->buf == '\0')
10271 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10272 if (strcmp (rs->buf, "OK") != 0)
10273 error (_("Error on target while enabling tracepoint."));
10277 remote_disable_tracepoint (struct bp_location *location)
10279 struct remote_state *rs = get_remote_state ();
10282 sprintf_vma (addr_buf, location->address);
10283 sprintf (rs->buf, "QTDisable:%x:%s", location->owner->number, addr_buf);
10285 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10286 if (*rs->buf == '\0')
10287 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10288 if (strcmp (rs->buf, "OK") != 0)
10289 error (_("Error on target while disabling tracepoint."));
10293 remote_trace_set_readonly_regions (void)
10296 bfd_size_type size;
10302 return; /* No information to give. */
10304 strcpy (target_buf, "QTro");
10305 for (s = exec_bfd->sections; s; s = s->next)
10307 char tmp1[40], tmp2[40];
10310 if ((s->flags & SEC_LOAD) == 0 ||
10311 /* (s->flags & SEC_CODE) == 0 || */
10312 (s->flags & SEC_READONLY) == 0)
10316 vma = bfd_get_section_vma (,s);
10317 size = bfd_get_section_size (s);
10318 sprintf_vma (tmp1, vma);
10319 sprintf_vma (tmp2, vma + size);
10320 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10321 if (offset + sec_length + 1 > target_buf_size)
10323 if (remote_protocol_packets[PACKET_qXfer_traceframe_info].support
10326 Too many sections for read-only sections definition packet."));
10329 sprintf (target_buf + offset, ":%s,%s", tmp1, tmp2);
10330 offset += sec_length;
10334 putpkt (target_buf);
10335 getpkt (&target_buf, &target_buf_size, 0);
10340 remote_trace_start (void)
10342 putpkt ("QTStart");
10343 remote_get_noisy_reply (&target_buf, &target_buf_size);
10344 if (*target_buf == '\0')
10345 error (_("Target does not support this command."));
10346 if (strcmp (target_buf, "OK") != 0)
10347 error (_("Bogus reply from target: %s"), target_buf);
10351 remote_get_trace_status (struct trace_status *ts)
10353 /* Initialize it just to avoid a GCC false warning. */
10355 /* FIXME we need to get register block size some other way. */
10356 extern int trace_regblock_size;
10357 volatile struct gdb_exception ex;
10359 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10361 putpkt ("qTStatus");
10363 TRY_CATCH (ex, RETURN_MASK_ERROR)
10365 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10369 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10373 /* If the remote target doesn't do tracing, flag it. */
10377 /* We're working with a live target. */
10380 /* Set some defaults. */
10381 ts->running_known = 0;
10382 ts->stop_reason = trace_stop_reason_unknown;
10383 ts->traceframe_count = -1;
10384 ts->buffer_free = 0;
10387 error (_("Bogus trace status reply from target: %s"), target_buf);
10389 parse_trace_status (p, ts);
10391 return ts->running;
10395 remote_get_tracepoint_status (struct breakpoint *bp,
10396 struct uploaded_tp *utp)
10398 struct remote_state *rs = get_remote_state ();
10400 struct bp_location *loc;
10401 struct tracepoint *tp = (struct tracepoint *) bp;
10405 tp->base.hit_count = 0;
10406 tp->traceframe_usage = 0;
10407 for (loc = tp->base.loc; loc; loc = loc->next)
10409 /* If the tracepoint was never downloaded, don't go asking for
10411 if (tp->number_on_target == 0)
10413 sprintf (rs->buf, "qTP:%x:%s", tp->number_on_target,
10414 phex_nz (loc->address, 0));
10416 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10417 if (reply && *reply)
10420 parse_tracepoint_status (reply + 1, bp, utp);
10426 utp->hit_count = 0;
10427 utp->traceframe_usage = 0;
10428 sprintf (rs->buf, "qTP:%x:%s", utp->number, phex_nz (utp->addr, 0));
10430 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10431 if (reply && *reply)
10434 parse_tracepoint_status (reply + 1, bp, utp);
10440 remote_trace_stop (void)
10443 remote_get_noisy_reply (&target_buf, &target_buf_size);
10444 if (*target_buf == '\0')
10445 error (_("Target does not support this command."));
10446 if (strcmp (target_buf, "OK") != 0)
10447 error (_("Bogus reply from target: %s"), target_buf);
10451 remote_trace_find (enum trace_find_type type, int num,
10452 ULONGEST addr1, ULONGEST addr2,
10455 struct remote_state *rs = get_remote_state ();
10457 int target_frameno = -1, target_tracept = -1;
10459 /* Lookups other than by absolute frame number depend on the current
10460 trace selected, so make sure it is correct on the remote end
10462 if (type != tfind_number)
10463 set_remote_traceframe ();
10466 strcpy (p, "QTFrame:");
10467 p = strchr (p, '\0');
10471 sprintf (p, "%x", num);
10474 sprintf (p, "pc:%s", phex_nz (addr1, 0));
10477 sprintf (p, "tdp:%x", num);
10480 sprintf (p, "range:%s:%s", phex_nz (addr1, 0), phex_nz (addr2, 0));
10482 case tfind_outside:
10483 sprintf (p, "outside:%s:%s", phex_nz (addr1, 0), phex_nz (addr2, 0));
10486 error (_("Unknown trace find type %d"), type);
10490 reply = remote_get_noisy_reply (&(rs->buf), &sizeof_pkt);
10491 if (*reply == '\0')
10492 error (_("Target does not support this command."));
10494 while (reply && *reply)
10499 target_frameno = (int) strtol (p, &reply, 16);
10501 error (_("Unable to parse trace frame number"));
10502 /* Don't update our remote traceframe number cache on failure
10503 to select a remote traceframe. */
10504 if (target_frameno == -1)
10509 target_tracept = (int) strtol (p, &reply, 16);
10511 error (_("Unable to parse tracepoint number"));
10513 case 'O': /* "OK"? */
10514 if (reply[1] == 'K' && reply[2] == '\0')
10517 error (_("Bogus reply from target: %s"), reply);
10520 error (_("Bogus reply from target: %s"), reply);
10523 *tpp = target_tracept;
10525 remote_traceframe_number = target_frameno;
10526 return target_frameno;
10530 remote_get_trace_state_variable_value (int tsvnum, LONGEST *val)
10532 struct remote_state *rs = get_remote_state ();
10536 set_remote_traceframe ();
10538 sprintf (rs->buf, "qTV:%x", tsvnum);
10540 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10541 if (reply && *reply)
10545 unpack_varlen_hex (reply + 1, &uval);
10546 *val = (LONGEST) uval;
10554 remote_save_trace_data (const char *filename)
10556 struct remote_state *rs = get_remote_state ();
10560 strcpy (p, "QTSave:");
10562 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
10563 error (_("Remote file name too long for trace save packet"));
10564 p += 2 * bin2hex ((gdb_byte *) filename, p, 0);
10567 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10568 if (*reply == '\0')
10569 error (_("Target does not support this command."));
10570 if (strcmp (reply, "OK") != 0)
10571 error (_("Bogus reply from target: %s"), reply);
10575 /* This is basically a memory transfer, but needs to be its own packet
10576 because we don't know how the target actually organizes its trace
10577 memory, plus we want to be able to ask for as much as possible, but
10578 not be unhappy if we don't get as much as we ask for. */
10581 remote_get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
10583 struct remote_state *rs = get_remote_state ();
10589 strcpy (p, "qTBuffer:");
10591 p += hexnumstr (p, offset);
10593 p += hexnumstr (p, len);
10597 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10598 if (reply && *reply)
10600 /* 'l' by itself means we're at the end of the buffer and
10601 there is nothing more to get. */
10605 /* Convert the reply into binary. Limit the number of bytes to
10606 convert according to our passed-in buffer size, rather than
10607 what was returned in the packet; if the target is
10608 unexpectedly generous and gives us a bigger reply than we
10609 asked for, we don't want to crash. */
10610 rslt = hex2bin (target_buf, buf, len);
10614 /* Something went wrong, flag as an error. */
10619 remote_set_disconnected_tracing (int val)
10621 struct remote_state *rs = get_remote_state ();
10623 if (rs->disconnected_tracing)
10627 sprintf (rs->buf, "QTDisconnected:%x", val);
10629 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10630 if (*reply == '\0')
10631 error (_("Target does not support this command."));
10632 if (strcmp (reply, "OK") != 0)
10633 error (_("Bogus reply from target: %s"), reply);
10636 warning (_("Target does not support disconnected tracing."));
10640 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
10642 struct thread_info *info = find_thread_ptid (ptid);
10644 if (info && info->private)
10645 return info->private->core;
10650 remote_set_circular_trace_buffer (int val)
10652 struct remote_state *rs = get_remote_state ();
10655 sprintf (rs->buf, "QTBuffer:circular:%x", val);
10657 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10658 if (*reply == '\0')
10659 error (_("Target does not support this command."));
10660 if (strcmp (reply, "OK") != 0)
10661 error (_("Bogus reply from target: %s"), reply);
10664 static struct traceframe_info *
10665 remote_traceframe_info (void)
10669 text = target_read_stralloc (¤t_target,
10670 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
10673 struct traceframe_info *info;
10674 struct cleanup *back_to = make_cleanup (xfree, text);
10676 info = parse_traceframe_info (text);
10677 do_cleanups (back_to);
10684 /* Handle the qTMinFTPILen packet. Returns the minimum length of
10685 instruction on which a fast tracepoint may be placed. Returns -1
10686 if the packet is not supported, and 0 if the minimum instruction
10687 length is unknown. */
10690 remote_get_min_fast_tracepoint_insn_len (void)
10692 struct remote_state *rs = get_remote_state ();
10695 /* If we're not debugging a process yet, the IPA can't be
10697 if (!target_has_execution)
10700 /* Make sure the remote is pointing at the right process. */
10701 set_general_process ();
10703 sprintf (rs->buf, "qTMinFTPILen");
10705 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10706 if (*reply == '\0')
10710 ULONGEST min_insn_len;
10712 unpack_varlen_hex (reply, &min_insn_len);
10714 return (int) min_insn_len;
10719 remote_set_trace_notes (char *user, char *notes, char *stop_notes)
10721 struct remote_state *rs = get_remote_state ();
10723 char *buf = rs->buf;
10724 char *endbuf = rs->buf + get_remote_packet_size ();
10727 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
10730 buf += xsnprintf (buf, endbuf - buf, "user:");
10731 nbytes = bin2hex (user, buf, 0);
10737 buf += xsnprintf (buf, endbuf - buf, "notes:");
10738 nbytes = bin2hex (notes, buf, 0);
10744 buf += xsnprintf (buf, endbuf - buf, "tstop:");
10745 nbytes = bin2hex (stop_notes, buf, 0);
10749 /* Ensure the buffer is terminated. */
10753 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10754 if (*reply == '\0')
10757 if (strcmp (reply, "OK") != 0)
10758 error (_("Bogus reply from target: %s"), reply);
10764 remote_use_agent (int use)
10766 if (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE)
10768 struct remote_state *rs = get_remote_state ();
10770 /* If the stub supports QAgent. */
10771 sprintf (rs->buf, "QAgent:%d", use);
10773 getpkt (&rs->buf, &rs->buf_size, 0);
10775 if (strcmp (rs->buf, "OK") == 0)
10786 remote_can_use_agent (void)
10788 return (remote_protocol_packets[PACKET_QAgent].support != PACKET_DISABLE);
10792 init_remote_ops (void)
10794 remote_ops.to_shortname = "remote";
10795 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
10796 remote_ops.to_doc =
10797 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
10798 Specify the serial device it is connected to\n\
10799 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
10800 remote_ops.to_open = remote_open;
10801 remote_ops.to_close = remote_close;
10802 remote_ops.to_detach = remote_detach;
10803 remote_ops.to_disconnect = remote_disconnect;
10804 remote_ops.to_resume = remote_resume;
10805 remote_ops.to_wait = remote_wait;
10806 remote_ops.to_fetch_registers = remote_fetch_registers;
10807 remote_ops.to_store_registers = remote_store_registers;
10808 remote_ops.to_prepare_to_store = remote_prepare_to_store;
10809 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
10810 remote_ops.to_files_info = remote_files_info;
10811 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
10812 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
10813 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
10814 remote_ops.to_stopped_data_address = remote_stopped_data_address;
10815 remote_ops.to_watchpoint_addr_within_range =
10816 remote_watchpoint_addr_within_range;
10817 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
10818 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
10819 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
10820 remote_ops.to_region_ok_for_hw_watchpoint
10821 = remote_region_ok_for_hw_watchpoint;
10822 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
10823 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
10824 remote_ops.to_kill = remote_kill;
10825 remote_ops.to_load = generic_load;
10826 remote_ops.to_mourn_inferior = remote_mourn;
10827 remote_ops.to_pass_signals = remote_pass_signals;
10828 remote_ops.to_thread_alive = remote_thread_alive;
10829 remote_ops.to_find_new_threads = remote_threads_info;
10830 remote_ops.to_pid_to_str = remote_pid_to_str;
10831 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10832 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
10833 remote_ops.to_stop = remote_stop;
10834 remote_ops.to_xfer_partial = remote_xfer_partial;
10835 remote_ops.to_rcmd = remote_rcmd;
10836 remote_ops.to_log_command = serial_log_command;
10837 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
10838 remote_ops.to_stratum = process_stratum;
10839 remote_ops.to_has_all_memory = default_child_has_all_memory;
10840 remote_ops.to_has_memory = default_child_has_memory;
10841 remote_ops.to_has_stack = default_child_has_stack;
10842 remote_ops.to_has_registers = default_child_has_registers;
10843 remote_ops.to_has_execution = default_child_has_execution;
10844 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
10845 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
10846 remote_ops.to_magic = OPS_MAGIC;
10847 remote_ops.to_memory_map = remote_memory_map;
10848 remote_ops.to_flash_erase = remote_flash_erase;
10849 remote_ops.to_flash_done = remote_flash_done;
10850 remote_ops.to_read_description = remote_read_description;
10851 remote_ops.to_search_memory = remote_search_memory;
10852 remote_ops.to_can_async_p = remote_can_async_p;
10853 remote_ops.to_is_async_p = remote_is_async_p;
10854 remote_ops.to_async = remote_async;
10855 remote_ops.to_terminal_inferior = remote_terminal_inferior;
10856 remote_ops.to_terminal_ours = remote_terminal_ours;
10857 remote_ops.to_supports_non_stop = remote_supports_non_stop;
10858 remote_ops.to_supports_multi_process = remote_supports_multi_process;
10859 remote_ops.to_supports_disable_randomization
10860 = remote_supports_disable_randomization;
10861 remote_ops.to_fileio_open = remote_hostio_open;
10862 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
10863 remote_ops.to_fileio_pread = remote_hostio_pread;
10864 remote_ops.to_fileio_close = remote_hostio_close;
10865 remote_ops.to_fileio_unlink = remote_hostio_unlink;
10866 remote_ops.to_fileio_readlink = remote_hostio_readlink;
10867 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
10868 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
10869 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
10870 remote_ops.to_trace_init = remote_trace_init;
10871 remote_ops.to_download_tracepoint = remote_download_tracepoint;
10872 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
10873 remote_ops.to_download_trace_state_variable
10874 = remote_download_trace_state_variable;
10875 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
10876 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
10877 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
10878 remote_ops.to_trace_start = remote_trace_start;
10879 remote_ops.to_get_trace_status = remote_get_trace_status;
10880 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
10881 remote_ops.to_trace_stop = remote_trace_stop;
10882 remote_ops.to_trace_find = remote_trace_find;
10883 remote_ops.to_get_trace_state_variable_value
10884 = remote_get_trace_state_variable_value;
10885 remote_ops.to_save_trace_data = remote_save_trace_data;
10886 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
10887 remote_ops.to_upload_trace_state_variables
10888 = remote_upload_trace_state_variables;
10889 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
10890 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
10891 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
10892 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
10893 remote_ops.to_set_trace_notes = remote_set_trace_notes;
10894 remote_ops.to_core_of_thread = remote_core_of_thread;
10895 remote_ops.to_verify_memory = remote_verify_memory;
10896 remote_ops.to_get_tib_address = remote_get_tib_address;
10897 remote_ops.to_set_permissions = remote_set_permissions;
10898 remote_ops.to_static_tracepoint_marker_at
10899 = remote_static_tracepoint_marker_at;
10900 remote_ops.to_static_tracepoint_markers_by_strid
10901 = remote_static_tracepoint_markers_by_strid;
10902 remote_ops.to_traceframe_info = remote_traceframe_info;
10903 remote_ops.to_use_agent = remote_use_agent;
10904 remote_ops.to_can_use_agent = remote_can_use_agent;
10907 /* Set up the extended remote vector by making a copy of the standard
10908 remote vector and adding to it. */
10911 init_extended_remote_ops (void)
10913 extended_remote_ops = remote_ops;
10915 extended_remote_ops.to_shortname = "extended-remote";
10916 extended_remote_ops.to_longname =
10917 "Extended remote serial target in gdb-specific protocol";
10918 extended_remote_ops.to_doc =
10919 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
10920 Specify the serial device it is connected to (e.g. /dev/ttya).";
10921 extended_remote_ops.to_open = extended_remote_open;
10922 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
10923 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
10924 extended_remote_ops.to_detach = extended_remote_detach;
10925 extended_remote_ops.to_attach = extended_remote_attach;
10926 extended_remote_ops.to_kill = extended_remote_kill;
10927 extended_remote_ops.to_supports_disable_randomization
10928 = extended_remote_supports_disable_randomization;
10932 remote_can_async_p (void)
10934 if (!target_async_permitted)
10935 /* We only enable async when the user specifically asks for it. */
10938 /* We're async whenever the serial device is. */
10939 return serial_can_async_p (remote_desc);
10943 remote_is_async_p (void)
10945 if (!target_async_permitted)
10946 /* We only enable async when the user specifically asks for it. */
10949 /* We're async whenever the serial device is. */
10950 return serial_is_async_p (remote_desc);
10953 /* Pass the SERIAL event on and up to the client. One day this code
10954 will be able to delay notifying the client of an event until the
10955 point where an entire packet has been received. */
10957 static void (*async_client_callback) (enum inferior_event_type event_type,
10959 static void *async_client_context;
10960 static serial_event_ftype remote_async_serial_handler;
10963 remote_async_serial_handler (struct serial *scb, void *context)
10965 /* Don't propogate error information up to the client. Instead let
10966 the client find out about the error by querying the target. */
10967 async_client_callback (INF_REG_EVENT, async_client_context);
10971 remote_async_inferior_event_handler (gdb_client_data data)
10973 inferior_event_handler (INF_REG_EVENT, NULL);
10977 remote_async_get_pending_events_handler (gdb_client_data data)
10979 remote_get_pending_stop_replies ();
10983 remote_async (void (*callback) (enum inferior_event_type event_type,
10984 void *context), void *context)
10986 if (callback != NULL)
10988 serial_async (remote_desc, remote_async_serial_handler, NULL);
10989 async_client_callback = callback;
10990 async_client_context = context;
10993 serial_async (remote_desc, NULL, NULL);
10997 set_remote_cmd (char *args, int from_tty)
10999 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
11003 show_remote_cmd (char *args, int from_tty)
11005 /* We can't just use cmd_show_list here, because we want to skip
11006 the redundant "show remote Z-packet" and the legacy aliases. */
11007 struct cleanup *showlist_chain;
11008 struct cmd_list_element *list = remote_show_cmdlist;
11009 struct ui_out *uiout = current_uiout;
11011 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
11012 for (; list != NULL; list = list->next)
11013 if (strcmp (list->name, "Z-packet") == 0)
11015 else if (list->type == not_set_cmd)
11016 /* Alias commands are exactly like the original, except they
11017 don't have the normal type. */
11021 struct cleanup *option_chain
11022 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
11024 ui_out_field_string (uiout, "name", list->name);
11025 ui_out_text (uiout, ": ");
11026 if (list->type == show_cmd)
11027 do_setshow_command ((char *) NULL, from_tty, list);
11029 cmd_func (list, NULL, from_tty);
11030 /* Close the tuple. */
11031 do_cleanups (option_chain);
11034 /* Close the tuple. */
11035 do_cleanups (showlist_chain);
11039 /* Function to be called whenever a new objfile (shlib) is detected. */
11041 remote_new_objfile (struct objfile *objfile)
11043 if (remote_desc != 0) /* Have a remote connection. */
11044 remote_check_symbols (objfile);
11047 /* Pull all the tracepoints defined on the target and create local
11048 data structures representing them. We don't want to create real
11049 tracepoints yet, we don't want to mess up the user's existing
11053 remote_upload_tracepoints (struct uploaded_tp **utpp)
11055 struct remote_state *rs = get_remote_state ();
11058 /* Ask for a first packet of tracepoint definition. */
11060 getpkt (&rs->buf, &rs->buf_size, 0);
11062 while (*p && *p != 'l')
11064 parse_tracepoint_definition (p, utpp);
11065 /* Ask for another packet of tracepoint definition. */
11067 getpkt (&rs->buf, &rs->buf_size, 0);
11074 remote_upload_trace_state_variables (struct uploaded_tsv **utsvp)
11076 struct remote_state *rs = get_remote_state ();
11079 /* Ask for a first packet of variable definition. */
11081 getpkt (&rs->buf, &rs->buf_size, 0);
11083 while (*p && *p != 'l')
11085 parse_tsv_definition (p, utsvp);
11086 /* Ask for another packet of variable definition. */
11088 getpkt (&rs->buf, &rs->buf_size, 0);
11095 _initialize_remote (void)
11097 struct remote_state *rs;
11098 struct cmd_list_element *cmd;
11101 /* architecture specific data */
11102 remote_gdbarch_data_handle =
11103 gdbarch_data_register_post_init (init_remote_state);
11104 remote_g_packet_data_handle =
11105 gdbarch_data_register_pre_init (remote_g_packet_data_init);
11107 /* Initialize the per-target state. At the moment there is only one
11108 of these, not one per target. Only one target is active at a
11109 time. The default buffer size is unimportant; it will be expanded
11110 whenever a larger buffer is needed. */
11111 rs = get_remote_state_raw ();
11112 rs->buf_size = 400;
11113 rs->buf = xmalloc (rs->buf_size);
11115 init_remote_ops ();
11116 add_target (&remote_ops);
11118 init_extended_remote_ops ();
11119 add_target (&extended_remote_ops);
11121 /* Hook into new objfile notification. */
11122 observer_attach_new_objfile (remote_new_objfile);
11124 /* Set up signal handlers. */
11125 sigint_remote_token =
11126 create_async_signal_handler (async_remote_interrupt, NULL);
11127 sigint_remote_twice_token =
11128 create_async_signal_handler (async_remote_interrupt_twice, NULL);
11131 init_remote_threadtests ();
11134 /* set/show remote ... */
11136 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
11137 Remote protocol specific variables\n\
11138 Configure various remote-protocol specific variables such as\n\
11139 the packets being used"),
11140 &remote_set_cmdlist, "set remote ",
11141 0 /* allow-unknown */, &setlist);
11142 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
11143 Remote protocol specific variables\n\
11144 Configure various remote-protocol specific variables such as\n\
11145 the packets being used"),
11146 &remote_show_cmdlist, "show remote ",
11147 0 /* allow-unknown */, &showlist);
11149 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
11150 Compare section data on target to the exec file.\n\
11151 Argument is a single section name (default: all loaded sections)."),
11154 add_cmd ("packet", class_maintenance, packet_command, _("\
11155 Send an arbitrary packet to a remote target.\n\
11156 maintenance packet TEXT\n\
11157 If GDB is talking to an inferior via the GDB serial protocol, then\n\
11158 this command sends the string TEXT to the inferior, and displays the\n\
11159 response packet. GDB supplies the initial `$' character, and the\n\
11160 terminating `#' character and checksum."),
11163 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
11164 Set whether to send break if interrupted."), _("\
11165 Show whether to send break if interrupted."), _("\
11166 If set, a break, instead of a cntrl-c, is sent to the remote target."),
11167 set_remotebreak, show_remotebreak,
11168 &setlist, &showlist);
11169 cmd_name = "remotebreak";
11170 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
11171 deprecate_cmd (cmd, "set remote interrupt-sequence");
11172 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
11173 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
11174 deprecate_cmd (cmd, "show remote interrupt-sequence");
11176 add_setshow_enum_cmd ("interrupt-sequence", class_support,
11177 interrupt_sequence_modes, &interrupt_sequence_mode,
11179 Set interrupt sequence to remote target."), _("\
11180 Show interrupt sequence to remote target."), _("\
11181 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
11182 NULL, show_interrupt_sequence,
11183 &remote_set_cmdlist,
11184 &remote_show_cmdlist);
11186 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
11187 &interrupt_on_connect, _("\
11188 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11189 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
11190 If set, interrupt sequence is sent to remote target."),
11192 &remote_set_cmdlist, &remote_show_cmdlist);
11194 /* Install commands for configuring memory read/write packets. */
11196 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
11197 Set the maximum number of bytes per memory write packet (deprecated)."),
11199 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
11200 Show the maximum number of bytes per memory write packet (deprecated)."),
11202 add_cmd ("memory-write-packet-size", no_class,
11203 set_memory_write_packet_size, _("\
11204 Set the maximum number of bytes per memory-write packet.\n\
11205 Specify the number of bytes in a packet or 0 (zero) for the\n\
11206 default packet size. The actual limit is further reduced\n\
11207 dependent on the target. Specify ``fixed'' to disable the\n\
11208 further restriction and ``limit'' to enable that restriction."),
11209 &remote_set_cmdlist);
11210 add_cmd ("memory-read-packet-size", no_class,
11211 set_memory_read_packet_size, _("\
11212 Set the maximum number of bytes per memory-read packet.\n\
11213 Specify the number of bytes in a packet or 0 (zero) for the\n\
11214 default packet size. The actual limit is further reduced\n\
11215 dependent on the target. Specify ``fixed'' to disable the\n\
11216 further restriction and ``limit'' to enable that restriction."),
11217 &remote_set_cmdlist);
11218 add_cmd ("memory-write-packet-size", no_class,
11219 show_memory_write_packet_size,
11220 _("Show the maximum number of bytes per memory-write packet."),
11221 &remote_show_cmdlist);
11222 add_cmd ("memory-read-packet-size", no_class,
11223 show_memory_read_packet_size,
11224 _("Show the maximum number of bytes per memory-read packet."),
11225 &remote_show_cmdlist);
11227 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
11228 &remote_hw_watchpoint_limit, _("\
11229 Set the maximum number of target hardware watchpoints."), _("\
11230 Show the maximum number of target hardware watchpoints."), _("\
11231 Specify a negative limit for unlimited."),
11232 NULL, NULL, /* FIXME: i18n: The maximum
11233 number of target hardware
11234 watchpoints is %s. */
11235 &remote_set_cmdlist, &remote_show_cmdlist);
11236 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
11237 &remote_hw_watchpoint_length_limit, _("\
11238 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
11239 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
11240 Specify a negative limit for unlimited."),
11241 NULL, NULL, /* FIXME: i18n: The maximum
11242 length (in bytes) of a target
11243 hardware watchpoint is %s. */
11244 &remote_set_cmdlist, &remote_show_cmdlist);
11245 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
11246 &remote_hw_breakpoint_limit, _("\
11247 Set the maximum number of target hardware breakpoints."), _("\
11248 Show the maximum number of target hardware breakpoints."), _("\
11249 Specify a negative limit for unlimited."),
11250 NULL, NULL, /* FIXME: i18n: The maximum
11251 number of target hardware
11252 breakpoints is %s. */
11253 &remote_set_cmdlist, &remote_show_cmdlist);
11255 add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
11256 &remote_address_size, _("\
11257 Set the maximum size of the address (in bits) in a memory packet."), _("\
11258 Show the maximum size of the address (in bits) in a memory packet."), NULL,
11260 NULL, /* FIXME: i18n: */
11261 &setlist, &showlist);
11263 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
11264 "X", "binary-download", 1);
11266 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
11267 "vCont", "verbose-resume", 0);
11269 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
11270 "QPassSignals", "pass-signals", 0);
11272 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
11273 "qSymbol", "symbol-lookup", 0);
11275 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
11276 "P", "set-register", 1);
11278 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
11279 "p", "fetch-register", 1);
11281 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
11282 "Z0", "software-breakpoint", 0);
11284 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
11285 "Z1", "hardware-breakpoint", 0);
11287 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
11288 "Z2", "write-watchpoint", 0);
11290 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
11291 "Z3", "read-watchpoint", 0);
11293 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
11294 "Z4", "access-watchpoint", 0);
11296 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
11297 "qXfer:auxv:read", "read-aux-vector", 0);
11299 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
11300 "qXfer:features:read", "target-features", 0);
11302 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
11303 "qXfer:libraries:read", "library-info", 0);
11305 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
11306 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
11308 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
11309 "qXfer:memory-map:read", "memory-map", 0);
11311 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
11312 "qXfer:spu:read", "read-spu-object", 0);
11314 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
11315 "qXfer:spu:write", "write-spu-object", 0);
11317 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
11318 "qXfer:osdata:read", "osdata", 0);
11320 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
11321 "qXfer:threads:read", "threads", 0);
11323 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
11324 "qXfer:siginfo:read", "read-siginfo-object", 0);
11326 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
11327 "qXfer:siginfo:write", "write-siginfo-object", 0);
11329 add_packet_config_cmd
11330 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
11331 "qXfer:trace-frame-info:read", "traceframe-info", 0);
11333 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
11334 "qGetTLSAddr", "get-thread-local-storage-address",
11337 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
11338 "qGetTIBAddr", "get-thread-information-block-address",
11341 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
11342 "bc", "reverse-continue", 0);
11344 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
11345 "bs", "reverse-step", 0);
11347 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
11348 "qSupported", "supported-packets", 0);
11350 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
11351 "qSearch:memory", "search-memory", 0);
11353 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
11354 "vFile:open", "hostio-open", 0);
11356 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
11357 "vFile:pread", "hostio-pread", 0);
11359 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
11360 "vFile:pwrite", "hostio-pwrite", 0);
11362 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
11363 "vFile:close", "hostio-close", 0);
11365 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
11366 "vFile:unlink", "hostio-unlink", 0);
11368 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
11369 "vFile:readlink", "hostio-readlink", 0);
11371 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
11372 "vAttach", "attach", 0);
11374 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
11377 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
11378 "QStartNoAckMode", "noack", 0);
11380 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
11381 "vKill", "kill", 0);
11383 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
11384 "qAttached", "query-attached", 0);
11386 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
11387 "ConditionalTracepoints",
11388 "conditional-tracepoints", 0);
11390 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
11391 "ConditionalBreakpoints",
11392 "conditional-breakpoints", 0);
11394 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
11395 "FastTracepoints", "fast-tracepoints", 0);
11397 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
11398 "TracepointSource", "TracepointSource", 0);
11400 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
11401 "QAllow", "allow", 0);
11403 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
11404 "StaticTracepoints", "static-tracepoints", 0);
11406 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
11407 "InstallInTrace", "install-in-trace", 0);
11409 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
11410 "qXfer:statictrace:read", "read-sdata-object", 0);
11412 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
11413 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
11415 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
11416 "QDisableRandomization", "disable-randomization", 0);
11418 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
11419 "QAgent", "agent", 0);
11421 /* Keep the old ``set remote Z-packet ...'' working. Each individual
11422 Z sub-packet has its own set and show commands, but users may
11423 have sets to this variable in their .gdbinit files (or in their
11425 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
11426 &remote_Z_packet_detect, _("\
11427 Set use of remote protocol `Z' packets"), _("\
11428 Show use of remote protocol `Z' packets "), _("\
11429 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
11431 set_remote_protocol_Z_packet_cmd,
11432 show_remote_protocol_Z_packet_cmd,
11433 /* FIXME: i18n: Use of remote protocol
11434 `Z' packets is %s. */
11435 &remote_set_cmdlist, &remote_show_cmdlist);
11437 add_prefix_cmd ("remote", class_files, remote_command, _("\
11438 Manipulate files on the remote system\n\
11439 Transfer files to and from the remote target system."),
11440 &remote_cmdlist, "remote ",
11441 0 /* allow-unknown */, &cmdlist);
11443 add_cmd ("put", class_files, remote_put_command,
11444 _("Copy a local file to the remote system."),
11447 add_cmd ("get", class_files, remote_get_command,
11448 _("Copy a remote file to the local system."),
11451 add_cmd ("delete", class_files, remote_delete_command,
11452 _("Delete a remote file."),
11455 remote_exec_file = xstrdup ("");
11456 add_setshow_string_noescape_cmd ("exec-file", class_files,
11457 &remote_exec_file, _("\
11458 Set the remote pathname for \"run\""), _("\
11459 Show the remote pathname for \"run\""), NULL, NULL, NULL,
11460 &remote_set_cmdlist, &remote_show_cmdlist);
11462 /* Eventually initialize fileio. See fileio.c */
11463 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
11465 /* Take advantage of the fact that the LWP field is not used, to tag
11466 special ptids with it set to != 0. */
11467 magic_null_ptid = ptid_build (42000, 1, -1);
11468 not_sent_ptid = ptid_build (42000, 1, -2);
11469 any_thread_ptid = ptid_build (42000, 1, 0);
11471 target_buf_size = 2048;
11472 target_buf = xmalloc (target_buf_size);