1 /* Remote target communications for serial-line targets in custom GDB protocol
2 Copyright 1988, 91, 92, 93, 94, 95, 96, 97, 98, 1999
3 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 2 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, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 /* See the GDB User Guide for details of the GDB remote protocol. */
25 #include "gdb_string.h"
34 /*#include "terminal.h" */
37 #include "gdb-stabs.h"
38 #include "gdbthread.h"
46 #include <sys/types.h>
49 #include "event-loop.h"
50 #include "event-top.h"
56 /* Prototypes for local functions */
57 static void cleanup_sigint_signal_handler (void *dummy);
58 static void initialize_sigint_signal_handler (void);
60 static void handle_remote_sigint PARAMS ((int));
61 static void handle_remote_sigint_twice PARAMS ((int));
62 static void async_remote_interrupt PARAMS ((gdb_client_data));
63 void async_remote_interrupt_twice PARAMS ((gdb_client_data));
65 static void build_remote_gdbarch_data PARAMS ((void));
67 static int remote_write_bytes (CORE_ADDR memaddr, char *myaddr, int len);
69 static int remote_read_bytes PARAMS ((CORE_ADDR memaddr,
70 char *myaddr, int len));
72 static void remote_files_info PARAMS ((struct target_ops * ignore));
74 static int remote_xfer_memory PARAMS ((CORE_ADDR memaddr, char *myaddr,
75 int len, int should_write,
76 struct target_ops * target));
78 static void remote_prepare_to_store PARAMS ((void));
80 static void remote_fetch_registers PARAMS ((int regno));
82 static void remote_resume PARAMS ((int pid, int step,
83 enum target_signal siggnal));
84 static void remote_async_resume PARAMS ((int pid, int step,
85 enum target_signal siggnal));
86 static int remote_start_remote PARAMS ((PTR));
88 static void remote_open PARAMS ((char *name, int from_tty));
89 static void remote_async_open PARAMS ((char *name, int from_tty));
91 static void extended_remote_open PARAMS ((char *name, int from_tty));
92 static void extended_remote_async_open PARAMS ((char *name, int from_tty));
94 static void remote_open_1 PARAMS ((char *, int, struct target_ops *,
96 static void remote_async_open_1 PARAMS ((char *, int, struct target_ops *,
99 static void remote_close PARAMS ((int quitting));
101 static void remote_store_registers PARAMS ((int regno));
103 static void remote_mourn PARAMS ((void));
104 static void remote_async_mourn PARAMS ((void));
106 static void extended_remote_restart PARAMS ((void));
108 static void extended_remote_mourn PARAMS ((void));
110 static void extended_remote_create_inferior PARAMS ((char *, char *, char **));
111 static void extended_remote_async_create_inferior PARAMS ((char *, char *, char **));
113 static void remote_mourn_1 PARAMS ((struct target_ops *));
115 static void remote_send PARAMS ((char *buf));
117 static int readchar PARAMS ((int timeout));
119 static int remote_wait PARAMS ((int pid, struct target_waitstatus * status));
120 static int remote_async_wait PARAMS ((int pid, struct target_waitstatus * status));
122 static void remote_kill PARAMS ((void));
123 static void remote_async_kill PARAMS ((void));
125 static int tohex PARAMS ((int nib));
127 static void remote_detach PARAMS ((char *args, int from_tty));
128 static void remote_async_detach PARAMS ((char *args, int from_tty));
130 static void remote_interrupt PARAMS ((int signo));
132 static void remote_interrupt_twice PARAMS ((int signo));
134 static void interrupt_query PARAMS ((void));
136 static void set_thread PARAMS ((int, int));
138 static int remote_thread_alive PARAMS ((int));
140 static void get_offsets PARAMS ((void));
142 static int read_frame PARAMS ((char *));
144 static int remote_insert_breakpoint PARAMS ((CORE_ADDR, char *));
146 static int remote_remove_breakpoint PARAMS ((CORE_ADDR, char *));
148 static int hexnumlen PARAMS ((ULONGEST num));
150 static void init_remote_ops PARAMS ((void));
152 static void init_extended_remote_ops PARAMS ((void));
154 static void init_remote_cisco_ops PARAMS ((void));
156 static struct target_ops remote_cisco_ops;
158 static void remote_stop PARAMS ((void));
160 static int ishex PARAMS ((int ch, int *val));
162 static int stubhex PARAMS ((int ch));
164 static int remote_query PARAMS ((int /*char */ , char *, char *, int *));
166 static int hexnumstr PARAMS ((char *, ULONGEST));
168 static int hexnumnstr PARAMS ((char *, ULONGEST, int));
170 static CORE_ADDR remote_address_masked PARAMS ((CORE_ADDR));
172 static void print_packet PARAMS ((char *));
174 static unsigned long crc32 PARAMS ((unsigned char *, int, unsigned int));
176 static void compare_sections_command PARAMS ((char *, int));
178 static void packet_command PARAMS ((char *, int));
180 static int stub_unpack_int PARAMS ((char *buff, int fieldlength));
182 static int remote_current_thread PARAMS ((int oldpid));
184 static void remote_find_new_threads PARAMS ((void));
186 static void record_currthread PARAMS ((int currthread));
188 /* exported functions */
190 extern int fromhex PARAMS ((int a));
192 static int putpkt_binary PARAMS ((char *buf, int cnt));
194 static void check_binary_download PARAMS ((CORE_ADDR addr));
196 struct packet_config;
198 static void show_packet_config_cmd PARAMS ((struct packet_config * config));
200 static void set_packet_config_cmd PARAMS ((struct packet_config * config,
201 struct cmd_list_element * c));
203 static void add_packet_config_cmd PARAMS ((struct packet_config * config,
206 void (*set_func) (char *args, int from_tty, struct cmd_list_element * c),
207 void (*show_func) (char *name, int from_tty),
208 struct cmd_list_element **setlist,
209 struct cmd_list_element **showlist));
211 static void init_packet_config PARAMS ((struct packet_config * config));
213 static void set_remote_protocol_P_packet_cmd PARAMS ((char *args,
215 struct cmd_list_element * c));
217 static void show_remote_protocol_P_packet_cmd PARAMS ((char *args,
220 static void set_remote_protocol_Z_packet_cmd PARAMS ((char *args,
222 struct cmd_list_element * c));
224 static void show_remote_protocol_Z_packet_cmd PARAMS ((char *args,
230 /* Define the target subroutine names */
232 void open_remote_target PARAMS ((char *, int, struct target_ops *, int));
234 void _initialize_remote PARAMS ((void));
238 static struct target_ops remote_ops;
240 static struct target_ops extended_remote_ops;
242 /* Temporary target ops. Just like the remote_ops and
243 extended_remote_ops, but with asynchronous support. */
244 static struct target_ops remote_async_ops;
246 static struct target_ops extended_async_remote_ops;
248 /* This was 5 seconds, which is a long time to sit and wait.
249 Unless this is going though some terminal server or multiplexer or
250 other form of hairy serial connection, I would think 2 seconds would
253 /* Changed to allow option to set timeout value.
254 was static int remote_timeout = 2; */
255 extern int remote_timeout;
257 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
258 ``forever'' still use the normal timeout mechanism. This is
259 currently used by the ASYNC code to guarentee that target reads
260 during the initial connect always time-out. Once getpkt has been
261 modified to return a timeout indication and, in turn
262 remote_wait()/wait_for_inferior() have gained a timeout parameter
264 static int wait_forever_enabled_p = 1;
267 /* This variable chooses whether to send a ^C or a break when the user
268 requests program interruption. Although ^C is usually what remote
269 systems expect, and that is the default here, sometimes a break is
270 preferable instead. */
272 static int remote_break;
274 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
275 remote_open knows that we don't have a file open when the program
277 static serial_t remote_desc = NULL;
279 /* This is set by the target (thru the 'S' message)
280 to denote that the target is in kernel mode. */
281 static int cisco_kernel_mode = 0;
283 /* This variable sets the number of bits in an address that are to be
284 sent in a memory ("M" or "m") packet. Normally, after stripping
285 leading zeros, the entire address would be sent. This variable
286 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
287 initial implementation of remote.c restricted the address sent in
288 memory packets to ``host::sizeof long'' bytes - (typically 32
289 bits). Consequently, for 64 bit targets, the upper 32 bits of an
290 address was never sent. Since fixing this bug may cause a break in
291 some remote targets this variable is principly provided to
292 facilitate backward compatibility. */
294 static int remote_address_size;
296 /* Tempoary to track who currently owns the terminal. See
297 target_async_terminal_* for more details. */
299 static int remote_async_terminal_ours_p;
302 /* This is the size (in chars) of the first response to the ``g''
303 packet. It is used as a heuristic when determining the maximum
304 size of memory-read and memory-write packets. A target will
305 typically only reserve a buffer large enough to hold the ``g''
306 packet. The size does not include packet overhead (headers and
309 static long actual_register_packet_size;
311 /* This is the maximum size (in chars) of a non read/write packet. It
312 is also used as a cap on the size of read/write packets. */
314 static long remote_packet_size;
316 #define PBUFSIZ (remote_packet_size)
318 /* User configurable variables for the number of characters in a
319 memory read/write packet. MIN (PBUFSIZ, g-packet-size) is the
320 default. Some targets need smaller values (fifo overruns, et.al.)
321 and some users need larger values (speed up transfers). The
322 variables ``preferred_*'' (the user request), ``current_*'' (what
323 was actually set) and ``forced_*'' (Positive - a soft limit,
324 negative - a hard limit). */
326 struct memory_packet_config
333 /* Compute the current size of a read/write packet. Since this makes
334 use of ``actual_register_packet_size'' the computation is dynamic. */
337 get_memory_packet_size (struct memory_packet_config *config)
339 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
340 law?) that some hosts don't cope very well with large alloca()
341 calls. Eventually the alloca() code will be replaced by calls to
342 xmalloc() and make_cleanups() allowing this restriction to either
343 be lifted or removed. */
344 #ifndef MAX_REMOTE_PACKET_SIZE
345 #define MAX_REMOTE_PACKET_SIZE 16384
347 /* NOTE: 16 is just chosen at random. */
348 #ifndef MIN_REMOTE_PACKET_SIZE
349 #define MIN_REMOTE_PACKET_SIZE 16
354 if (config->size <= 0)
355 what_they_get = MAX_REMOTE_PACKET_SIZE;
357 what_they_get = config->size;
361 what_they_get = remote_packet_size;
362 /* Limit the packet to the size specified by the user. */
364 && what_they_get > config->size)
365 what_they_get = config->size;
366 /* Limit it to the size of the targets ``g'' response. */
367 if (actual_register_packet_size > 0
368 && what_they_get > actual_register_packet_size)
369 what_they_get = actual_register_packet_size;
371 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
372 what_they_get = MAX_REMOTE_PACKET_SIZE;
373 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
374 what_they_get = MIN_REMOTE_PACKET_SIZE;
375 return what_they_get;
378 /* Update the size of a read/write packet. If they user wants
379 something really big then do a sanity check. */
382 set_memory_packet_size (char *args, struct memory_packet_config *config)
384 int fixed_p = config->fixed_p;
385 long size = config->size;
387 error ("Argument required (integer, `fixed' or `limited').");
388 else if (strcmp (args, "hard") == 0
389 || strcmp (args, "fixed") == 0)
391 else if (strcmp (args, "soft") == 0
392 || strcmp (args, "limit") == 0)
397 size = strtoul (args, &end, 0);
399 error ("Invalid %s (bad syntax).", config->name);
401 /* Instead of explicitly capping the size of a packet to
402 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
403 instead allowed to set the size to something arbitrarily
405 if (size > MAX_REMOTE_PACKET_SIZE)
406 error ("Invalid %s (too large).", config->name);
410 if (fixed_p && !config->fixed_p)
412 if (! query ("The target may not be able to correctly handle a %s\n"
413 "of %ld bytes. Change the packet size? ",
415 error ("Packet size not changed.");
417 /* Update the config. */
418 config->fixed_p = fixed_p;
423 show_memory_packet_size (struct memory_packet_config *config)
425 printf_filtered ("The %s is %ld. ", config->name, config->size);
427 printf_filtered ("Packets are fixed at %ld bytes.\n",
428 get_memory_packet_size (config));
430 printf_filtered ("Packets are limited to %ld bytes.\n",
431 get_memory_packet_size (config));
434 static struct memory_packet_config memory_write_packet_config =
436 "memory-write-packet-size",
440 set_memory_write_packet_size (char *args, int from_tty)
442 set_memory_packet_size (args, &memory_write_packet_config);
446 show_memory_write_packet_size (char *args, int from_tty)
448 show_memory_packet_size (&memory_write_packet_config);
452 get_memory_write_packet_size (void)
454 return get_memory_packet_size (&memory_write_packet_config);
457 static struct memory_packet_config memory_read_packet_config =
459 "memory-read-packet-size",
463 set_memory_read_packet_size (char *args, int from_tty)
465 set_memory_packet_size (args, &memory_read_packet_config);
469 show_memory_read_packet_size (char *args, int from_tty)
471 show_memory_packet_size (&memory_read_packet_config);
475 get_memory_read_packet_size (void)
477 long size = get_memory_packet_size (&memory_read_packet_config);
478 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
479 extra buffer size argument before the memory read size can be
480 increased beyond PBUFSIZ. */
486 /* Register packet size initialization. Since the bounds change when
487 the architecture changes (namely REGISTER_BYTES) this all needs to
491 register_remote_packet_sizes (void)
493 REGISTER_GDBARCH_SWAP (remote_packet_size);
494 REGISTER_GDBARCH_SWAP (actual_register_packet_size);
498 build_remote_packet_sizes (void)
500 /* Maximum number of characters in a packet. This default m68k-stub.c and
501 i386-stub.c stubs. */
502 remote_packet_size = 400;
503 /* Should REGISTER_BYTES needs more space than the default, adjust
504 the size accordingly. Remember that each byte is encoded as two
505 characters. 32 is the overhead for the packet header /
506 footer. NOTE: cagney/1999-10-26: I suspect that 8
507 (``$NN:G...#NN'') is a better guess, the below has been padded a
509 if (REGISTER_BYTES > ((remote_packet_size - 32) / 2))
510 remote_packet_size = (REGISTER_BYTES * 2 + 32);
512 /* This one is filled in when a ``g'' packet is received. */
513 actual_register_packet_size = 0;
516 /* Generic configuration support for packets the stub optionally
517 supports. Allows the user to specify the use of the packet as well
518 as allowing GDB to auto-detect support in the remote stub. */
522 PACKET_SUPPORT_UNKNOWN = 0,
529 PACKET_AUTO_DETECT = 0,
538 enum packet_detect detect;
539 enum packet_support support;
542 static char packet_support_auto[] = "auto";
543 static char packet_enable[] = "enable";
544 static char packet_disable[] = "disable";
545 static char *packet_support_enums[] =
554 set_packet_config_cmd (config, c)
555 struct packet_config *config;
556 struct cmd_list_element *c;
558 if (config->state == packet_enable)
560 config->detect = PACKET_MANUAL_DETECT;
561 config->support = PACKET_ENABLE;
563 else if (config->state == packet_disable)
565 config->detect = PACKET_MANUAL_DETECT;
566 config->support = PACKET_DISABLE;
568 else if (config->state == packet_support_auto)
570 config->detect = PACKET_AUTO_DETECT;
571 config->support = PACKET_SUPPORT_UNKNOWN;
574 internal_error ("Bad enum value");
578 show_packet_config_cmd (config)
579 struct packet_config *config;
581 char *support = "internal-error";
582 switch (config->support)
588 support = "disabled";
590 case PACKET_SUPPORT_UNKNOWN:
594 switch (config->detect)
596 case PACKET_AUTO_DETECT:
597 printf_filtered ("Support for remote protocol `%s' (%s) packet is auto-detected, currently %s.\n",
598 config->name, config->title, support);
600 case PACKET_MANUAL_DETECT:
601 printf_filtered ("Support for remote protocol `%s' (%s) is currently %s.\n",
602 config->name, config->title, support);
607 add_packet_config_cmd (config, name, title, set_func, show_func,
609 struct packet_config *config;
612 void (*set_func) PARAMS ((char *args, int from_tty,
613 struct cmd_list_element * c));
614 void (*show_func) PARAMS ((char *name, int from_tty));
615 struct cmd_list_element **setlist;
616 struct cmd_list_element **showlist;
618 struct cmd_list_element *c;
623 config->title = title;
624 asprintf (&set_doc, "Set use of remote protocol `%s' (%s) packet",
626 asprintf (&show_doc, "Show current use of remote protocol `%s' (%s) packet",
628 asprintf (&full_name, "%s-packet", name);
629 c = add_set_enum_cmd (full_name,
630 class_obscure, packet_support_enums,
631 (char *) &config->state,
633 c->function.sfunc = set_func;
634 add_cmd (full_name, class_obscure, show_func, show_doc, showlist);
638 init_packet_config (config)
639 struct packet_config *config;
641 switch (config->detect)
643 case PACKET_AUTO_DETECT:
644 config->support = PACKET_SUPPORT_UNKNOWN;
646 case PACKET_MANUAL_DETECT:
647 /* let the user beware */
652 /* Should we try the 'P' (set register) request? */
654 static struct packet_config remote_protocol_P;
657 set_remote_protocol_P_packet_cmd (args, from_tty, c)
660 struct cmd_list_element *c;
662 set_packet_config_cmd (&remote_protocol_P, c);
666 show_remote_protocol_P_packet_cmd (args, from_tty)
670 show_packet_config_cmd (&remote_protocol_P);
673 /* Should we try the 'Z' (set breakpoint) request? */
675 static struct packet_config remote_protocol_Z;
678 set_remote_protocol_Z_packet_cmd (args, from_tty, c)
681 struct cmd_list_element *c;
683 set_packet_config_cmd (&remote_protocol_Z, c);
687 show_remote_protocol_Z_packet_cmd (args, from_tty)
691 show_packet_config_cmd (&remote_protocol_Z);
694 /* Should we try the 'X' (remote binary download) packet?
696 This variable (available to the user via "set remote X-packet")
697 dictates whether downloads are sent in binary (via the 'X' packet).
698 We assume that the stub can, and attempt to do it. This will be
699 cleared if the stub does not understand it. This switch is still
700 needed, though in cases when the packet is supported in the stub,
701 but the connection does not allow it (i.e., 7-bit serial connection
704 static struct packet_config remote_protocol_binary_download;
707 set_remote_protocol_binary_download_cmd (char *args,
709 struct cmd_list_element *c)
711 set_packet_config_cmd (&remote_protocol_binary_download, c);
715 show_remote_protocol_binary_download_cmd (char *args,
718 show_packet_config_cmd (&remote_protocol_binary_download);
722 /* Tokens for use by the asynchronous signal handlers for SIGINT */
723 PTR sigint_remote_twice_token;
724 PTR sigint_remote_token;
726 /* These are pointers to hook functions that may be set in order to
727 modify resume/wait behavior for a particular architecture. */
729 void (*target_resume_hook) PARAMS ((void));
730 void (*target_wait_loop_hook) PARAMS ((void));
734 /* These are the threads which we last sent to the remote system.
735 -1 for all or -2 for not sent yet. */
736 static int general_thread;
737 static int continue_thread;
739 /* Call this function as a result of
740 1) A halt indication (T packet) containing a thread id
741 2) A direct query of currthread
742 3) Successful execution of set thread
746 record_currthread (currthread)
749 general_thread = currthread;
751 /* If this is a new thread, add it to GDB's thread list.
752 If we leave it up to WFI to do this, bad things will happen. */
753 if (!in_thread_list (currthread))
755 add_thread (currthread);
756 printf_filtered ("[New %s]\n", target_pid_to_str (currthread));
760 #define MAGIC_NULL_PID 42000
767 char *buf = alloca (PBUFSIZ);
768 int state = gen ? general_thread : continue_thread;
774 buf[1] = gen ? 'g' : 'c';
775 if (th == MAGIC_NULL_PID)
781 sprintf (&buf[2], "-%x", -th);
783 sprintf (&buf[2], "%x", th);
789 continue_thread = th;
792 /* Return nonzero if the thread TH is still alive on the remote system. */
795 remote_thread_alive (tid)
801 sprintf (buf, "T-%08x", -tid);
803 sprintf (buf, "T%08x", tid);
806 return (buf[0] == 'O' && buf[1] == 'K');
809 /* About these extended threadlist and threadinfo packets. They are
810 variable length packets but, the fields within them are often fixed
811 length. They are redundent enough to send over UDP as is the
812 remote protocol in general. There is a matching unit test module
815 #define OPAQUETHREADBYTES 8
817 /* a 64 bit opaque identifier */
818 typedef unsigned char threadref[OPAQUETHREADBYTES];
820 /* WARNING: This threadref data structure comes from the remote O.S., libstub
821 protocol encoding, and remote.c. it is not particularly changable */
823 /* Right now, the internal structure is int. We want it to be bigger.
827 typedef int gdb_threadref; /* internal GDB thread reference */
829 /* gdb_ext_thread_info is an internal GDB data structure which is
830 equivalint to the reply of the remote threadinfo packet */
832 struct gdb_ext_thread_info
834 threadref threadid; /* External form of thread reference */
835 int active; /* Has state interesting to GDB? , regs, stack */
836 char display[256]; /* Brief state display, name, blocked/syspended */
837 char shortname[32]; /* To be used to name threads */
838 char more_display[256]; /* Long info, statistics, queue depth, whatever */
841 /* The volume of remote transfers can be limited by submitting
842 a mask containing bits specifying the desired information.
843 Use a union of these values as the 'selection' parameter to
844 get_thread_info. FIXME: Make these TAG names more thread specific.
847 #define TAG_THREADID 1
849 #define TAG_DISPLAY 4
850 #define TAG_THREADNAME 8
851 #define TAG_MOREDISPLAY 16
853 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES*2)
855 char *unpack_varlen_hex PARAMS ((char *buff, int *result));
857 static char *unpack_nibble PARAMS ((char *buf, int *val));
859 static char *pack_nibble PARAMS ((char *buf, int nibble));
861 static char *pack_hex_byte PARAMS ((char *pkt, int /*unsigned char */ byte));
863 static char *unpack_byte PARAMS ((char *buf, int *value));
865 static char *pack_int PARAMS ((char *buf, int value));
867 static char *unpack_int PARAMS ((char *buf, int *value));
869 static char *unpack_string PARAMS ((char *src, char *dest, int length));
871 static char *pack_threadid PARAMS ((char *pkt, threadref * id));
873 static char *unpack_threadid PARAMS ((char *inbuf, threadref * id));
875 void int_to_threadref PARAMS ((threadref * id, int value));
877 static int threadref_to_int PARAMS ((threadref * ref));
879 static void copy_threadref PARAMS ((threadref * dest, threadref * src));
881 static int threadmatch PARAMS ((threadref * dest, threadref * src));
883 static char *pack_threadinfo_request PARAMS ((char *pkt, int mode,
886 static int remote_unpack_thread_info_response PARAMS ((char *pkt,
887 threadref * expectedref,
888 struct gdb_ext_thread_info * info));
891 static int remote_get_threadinfo PARAMS ((threadref * threadid,
892 int fieldset, /*TAG mask */
893 struct gdb_ext_thread_info * info));
895 static int adapt_remote_get_threadinfo PARAMS ((gdb_threadref * ref,
897 struct gdb_ext_thread_info * info));
899 static char *pack_threadlist_request PARAMS ((char *pkt, int startflag,
901 threadref * nextthread));
903 static int parse_threadlist_response PARAMS ((char *pkt,
905 threadref * original_echo,
906 threadref * resultlist,
909 static int remote_get_threadlist PARAMS ((int startflag,
910 threadref * nextthread,
914 threadref * threadlist));
916 typedef int (*rmt_thread_action) (threadref * ref, void *context);
918 static int remote_threadlist_iterator PARAMS ((rmt_thread_action stepfunction,
919 void *context, int looplimit));
921 static int remote_newthread_step PARAMS ((threadref * ref, void *context));
923 /* encode 64 bits in 16 chars of hex */
925 static const char hexchars[] = "0123456789abcdef";
932 if ((ch >= 'a') && (ch <= 'f'))
934 *val = ch - 'a' + 10;
937 if ((ch >= 'A') && (ch <= 'F'))
939 *val = ch - 'A' + 10;
942 if ((ch >= '0') && (ch <= '9'))
954 if (ch >= 'a' && ch <= 'f')
955 return ch - 'a' + 10;
956 if (ch >= '0' && ch <= '9')
958 if (ch >= 'A' && ch <= 'F')
959 return ch - 'A' + 10;
964 stub_unpack_int (buff, fieldlength)
973 nibble = stubhex (*buff++);
977 retval = retval << 4;
983 unpack_varlen_hex (buff, result)
984 char *buff; /* packet to parse */
990 while (ishex (*buff, &nibble))
993 retval = retval << 4;
994 retval |= nibble & 0x0f;
1001 unpack_nibble (buf, val)
1005 ishex (*buf++, val);
1010 pack_nibble (buf, nibble)
1014 *buf++ = hexchars[(nibble & 0x0f)];
1019 pack_hex_byte (pkt, byte)
1023 *pkt++ = hexchars[(byte >> 4) & 0xf];
1024 *pkt++ = hexchars[(byte & 0xf)];
1029 unpack_byte (buf, value)
1033 *value = stub_unpack_int (buf, 2);
1038 pack_int (buf, value)
1042 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
1043 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
1044 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
1045 buf = pack_hex_byte (buf, (value & 0xff));
1050 unpack_int (buf, value)
1054 *value = stub_unpack_int (buf, 8);
1058 #if 0 /* currently unused, uncomment when needed */
1059 static char *pack_string PARAMS ((char *pkt, char *string));
1062 pack_string (pkt, string)
1069 len = strlen (string);
1071 len = 200; /* Bigger than most GDB packets, junk??? */
1072 pkt = pack_hex_byte (pkt, len);
1076 if ((ch == '\0') || (ch == '#'))
1077 ch = '*'; /* Protect encapsulation */
1082 #endif /* 0 (unused) */
1085 unpack_string (src, dest, length)
1097 pack_threadid (pkt, id)
1102 unsigned char *altid;
1104 altid = (unsigned char *) id;
1105 limit = pkt + BUF_THREAD_ID_SIZE;
1107 pkt = pack_hex_byte (pkt, *altid++);
1113 unpack_threadid (inbuf, id)
1118 char *limit = inbuf + BUF_THREAD_ID_SIZE;
1121 altref = (char *) id;
1123 while (inbuf < limit)
1125 x = stubhex (*inbuf++);
1126 y = stubhex (*inbuf++);
1127 *altref++ = (x << 4) | y;
1132 /* Externally, threadrefs are 64 bits but internally, they are still
1133 ints. This is due to a mismatch of specifications. We would like
1134 to use 64bit thread references internally. This is an adapter
1138 int_to_threadref (id, value)
1142 unsigned char *scan;
1144 scan = (unsigned char *) id;
1150 *scan++ = (value >> 24) & 0xff;
1151 *scan++ = (value >> 16) & 0xff;
1152 *scan++ = (value >> 8) & 0xff;
1153 *scan++ = (value & 0xff);
1157 threadref_to_int (ref)
1161 unsigned char *scan;
1163 scan = (char *) ref;
1167 value = (value << 8) | ((*scan++) & 0xff);
1172 copy_threadref (dest, src)
1177 unsigned char *csrc, *cdest;
1179 csrc = (unsigned char *) src;
1180 cdest = (unsigned char *) dest;
1187 threadmatch (dest, src)
1191 /* things are broken right now, so just assume we got a match */
1193 unsigned char *srcp, *destp;
1195 srcp = (char *) src;
1196 destp = (char *) dest;
1200 result &= (*srcp++ == *destp++) ? 1 : 0;
1207 threadid:1, # always request threadid
1214 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
1217 pack_threadinfo_request (pkt, mode, id)
1222 *pkt++ = 'q'; /* Info Query */
1223 *pkt++ = 'P'; /* process or thread info */
1224 pkt = pack_int (pkt, mode); /* mode */
1225 pkt = pack_threadid (pkt, id); /* threadid */
1226 *pkt = '\0'; /* terminate */
1230 /* These values tag the fields in a thread info response packet */
1231 /* Tagging the fields allows us to request specific fields and to
1232 add more fields as time goes by */
1234 #define TAG_THREADID 1 /* Echo the thread identifier */
1235 #define TAG_EXISTS 2 /* Is this process defined enough to
1236 fetch registers and its stack */
1237 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
1238 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is */
1239 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
1243 remote_unpack_thread_info_response (pkt, expectedref, info)
1245 threadref *expectedref;
1246 struct gdb_ext_thread_info *info;
1251 char *limit = pkt + PBUFSIZ; /* plausable parsing limit */
1254 /* info->threadid = 0; FIXME: implement zero_threadref */
1256 info->display[0] = '\0';
1257 info->shortname[0] = '\0';
1258 info->more_display[0] = '\0';
1260 /* Assume the characters indicating the packet type have been stripped */
1261 pkt = unpack_int (pkt, &mask); /* arg mask */
1262 pkt = unpack_threadid (pkt, &ref);
1265 warning ("Incomplete response to threadinfo request\n");
1266 if (!threadmatch (&ref, expectedref))
1267 { /* This is an answer to a different request */
1268 warning ("ERROR RMT Thread info mismatch\n");
1271 copy_threadref (&info->threadid, &ref);
1273 /* Loop on tagged fields , try to bail if somthing goes wrong */
1275 while ((pkt < limit) && mask && *pkt) /* packets are terminated with nulls */
1277 pkt = unpack_int (pkt, &tag); /* tag */
1278 pkt = unpack_byte (pkt, &length); /* length */
1279 if (!(tag & mask)) /* tags out of synch with mask */
1281 warning ("ERROR RMT: threadinfo tag mismatch\n");
1285 if (tag == TAG_THREADID)
1289 warning ("ERROR RMT: length of threadid is not 16\n");
1293 pkt = unpack_threadid (pkt, &ref);
1294 mask = mask & ~TAG_THREADID;
1297 if (tag == TAG_EXISTS)
1299 info->active = stub_unpack_int (pkt, length);
1301 mask = mask & ~(TAG_EXISTS);
1304 warning ("ERROR RMT: 'exists' length too long\n");
1310 if (tag == TAG_THREADNAME)
1312 pkt = unpack_string (pkt, &info->shortname[0], length);
1313 mask = mask & ~TAG_THREADNAME;
1316 if (tag == TAG_DISPLAY)
1318 pkt = unpack_string (pkt, &info->display[0], length);
1319 mask = mask & ~TAG_DISPLAY;
1322 if (tag == TAG_MOREDISPLAY)
1324 pkt = unpack_string (pkt, &info->more_display[0], length);
1325 mask = mask & ~TAG_MOREDISPLAY;
1328 warning ("ERROR RMT: unknown thread info tag\n");
1329 break; /* Not a tag we know about */
1335 remote_get_threadinfo (threadid, fieldset, info)
1336 threadref *threadid;
1337 int fieldset; /* TAG mask */
1338 struct gdb_ext_thread_info *info;
1341 char *threadinfo_pkt = alloca (PBUFSIZ);
1343 pack_threadinfo_request (threadinfo_pkt, fieldset, threadid);
1344 putpkt (threadinfo_pkt);
1345 getpkt (threadinfo_pkt, 0);
1346 result = remote_unpack_thread_info_response (threadinfo_pkt + 2, threadid,
1351 /* Unfortunately, 61 bit thread-ids are bigger than the internal
1352 representation of a threadid. */
1355 adapt_remote_get_threadinfo (ref, selection, info)
1358 struct gdb_ext_thread_info *info;
1362 int_to_threadref (&lclref, *ref);
1363 return remote_get_threadinfo (&lclref, selection, info);
1366 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
1369 pack_threadlist_request (pkt, startflag, threadcount, nextthread)
1373 threadref *nextthread;
1375 *pkt++ = 'q'; /* info query packet */
1376 *pkt++ = 'L'; /* Process LIST or threadLIST request */
1377 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
1378 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
1379 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
1384 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
1387 parse_threadlist_response (pkt, result_limit, original_echo, resultlist,
1391 threadref *original_echo;
1392 threadref *resultlist;
1396 int count, resultcount, done;
1399 /* Assume the 'q' and 'M chars have been stripped. */
1400 limit = pkt + (PBUFSIZ - BUF_THREAD_ID_SIZE); /* done parse past here */
1401 pkt = unpack_byte (pkt, &count); /* count field */
1402 pkt = unpack_nibble (pkt, &done);
1403 /* The first threadid is the argument threadid. */
1404 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
1405 while ((count-- > 0) && (pkt < limit))
1407 pkt = unpack_threadid (pkt, resultlist++);
1408 if (resultcount++ >= result_limit)
1417 remote_get_threadlist (startflag, nextthread, result_limit,
1418 done, result_count, threadlist)
1420 threadref *nextthread;
1424 threadref *threadlist;
1427 static threadref echo_nextthread;
1428 char *threadlist_packet = alloca (PBUFSIZ);
1429 char *t_response = alloca (PBUFSIZ);
1432 /* Trancate result limit to be smaller than the packet size */
1433 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= PBUFSIZ)
1434 result_limit = (PBUFSIZ / BUF_THREAD_ID_SIZE) - 2;
1436 pack_threadlist_request (threadlist_packet,
1437 startflag, result_limit, nextthread);
1438 putpkt (threadlist_packet);
1439 getpkt (t_response, 0);
1442 parse_threadlist_response (t_response + 2, result_limit, &echo_nextthread,
1445 if (!threadmatch (&echo_nextthread, nextthread))
1447 /* FIXME: This is a good reason to drop the packet */
1448 /* Possably, there is a duplicate response */
1450 retransmit immediatly - race conditions
1451 retransmit after timeout - yes
1453 wait for packet, then exit
1455 warning ("HMM: threadlist did not echo arg thread, dropping it\n");
1456 return 0; /* I choose simply exiting */
1458 if (*result_count <= 0)
1462 warning ("RMT ERROR : failed to get remote thread list\n");
1465 return result; /* break; */
1467 if (*result_count > result_limit)
1470 warning ("RMT ERROR: threadlist response longer than requested\n");
1476 /* This is the interface between remote and threads, remotes upper interface */
1478 /* remote_find_new_threads retrieves the thread list and for each
1479 thread in the list, looks up the thread in GDB's internal list,
1480 ading the thread if it does not already exist. This involves
1481 getting partial thread lists from the remote target so, polling the
1482 quit_flag is required. */
1485 /* About this many threadisds fit in a packet. */
1487 #define MAXTHREADLISTRESULTS 32
1490 remote_threadlist_iterator (stepfunction, context, looplimit)
1491 rmt_thread_action stepfunction;
1495 int done, i, result_count;
1499 static threadref nextthread;
1500 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
1505 if (loopcount++ > looplimit)
1508 warning ("Remote fetch threadlist -infinite loop-\n");
1511 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
1512 &done, &result_count, resultthreadlist))
1517 /* clear for later iterations */
1519 /* Setup to resume next batch of thread references, set nextthread. */
1520 if (result_count >= 1)
1521 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
1523 while (result_count--)
1524 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
1531 remote_newthread_step (ref, context)
1537 pid = threadref_to_int (ref);
1538 if (!in_thread_list (pid))
1540 return 1; /* continue iterator */
1543 #define CRAZY_MAX_THREADS 1000
1546 remote_current_thread (oldpid)
1549 char *buf = alloca (PBUFSIZ);
1553 if (buf[0] == 'Q' && buf[1] == 'C')
1554 return strtol (&buf[2], NULL, 16);
1559 /* Find new threads for info threads command. */
1562 remote_find_new_threads ()
1564 remote_threadlist_iterator (remote_newthread_step, 0,
1566 if (inferior_pid == MAGIC_NULL_PID) /* ack ack ack */
1567 inferior_pid = remote_current_thread (inferior_pid);
1571 remote_threads_info (void)
1573 char *buf = alloca (PBUFSIZ);
1577 if (remote_desc == 0) /* paranoia */
1578 error ("Command can only be used when connected to the remote target.");
1580 putpkt ("qfThreadInfo");
1581 getpkt (bufp = buf, 0);
1582 if (bufp[0] == '\0') /* q packet not recognized! */
1583 { /* try old jmetzler method */
1584 remote_find_new_threads ();
1587 else /* try new 'q' method */
1588 while (*bufp++ == 'm') /* reply contains one or more TID */
1592 tid = strtol (bufp, &bufp, 16);
1593 if (tid != 0 && !in_thread_list (tid))
1596 while (*bufp++ == ','); /* comma-separated list */
1597 putpkt ("qsThreadInfo");
1598 getpkt (bufp = buf, 0);
1603 /* Restart the remote side; this is an extended protocol operation. */
1606 extended_remote_restart ()
1608 char *buf = alloca (PBUFSIZ);
1610 /* Send the restart command; for reasons I don't understand the
1611 remote side really expects a number after the "R". */
1613 sprintf (&buf[1], "%x", 0);
1616 /* Now query for status so this looks just like we restarted
1617 gdbserver from scratch. */
1622 /* Clean up connection to a remote debugger. */
1626 remote_close (quitting)
1630 SERIAL_CLOSE (remote_desc);
1634 /* Query the remote side for the text, data and bss offsets. */
1639 char *buf = alloca (PBUFSIZ);
1642 CORE_ADDR text_addr, data_addr, bss_addr;
1643 struct section_offsets *offs;
1645 putpkt ("qOffsets");
1649 if (buf[0] == '\000')
1650 return; /* Return silently. Stub doesn't support
1654 warning ("Remote failure reply: %s", buf);
1658 /* Pick up each field in turn. This used to be done with scanf, but
1659 scanf will make trouble if CORE_ADDR size doesn't match
1660 conversion directives correctly. The following code will work
1661 with any size of CORE_ADDR. */
1662 text_addr = data_addr = bss_addr = 0;
1666 if (strncmp (ptr, "Text=", 5) == 0)
1669 /* Don't use strtol, could lose on big values. */
1670 while (*ptr && *ptr != ';')
1671 text_addr = (text_addr << 4) + fromhex (*ptr++);
1676 if (!lose && strncmp (ptr, ";Data=", 6) == 0)
1679 while (*ptr && *ptr != ';')
1680 data_addr = (data_addr << 4) + fromhex (*ptr++);
1685 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
1688 while (*ptr && *ptr != ';')
1689 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
1695 error ("Malformed response to offset query, %s", buf);
1697 if (symfile_objfile == NULL)
1700 offs = (struct section_offsets *) alloca (SIZEOF_SECTION_OFFSETS);
1701 memcpy (offs, symfile_objfile->section_offsets, SIZEOF_SECTION_OFFSETS);
1703 ANOFFSET (offs, SECT_OFF_TEXT) = text_addr;
1705 /* This is a temporary kludge to force data and bss to use the same offsets
1706 because that's what nlmconv does now. The real solution requires changes
1707 to the stub and remote.c that I don't have time to do right now. */
1709 ANOFFSET (offs, SECT_OFF_DATA) = data_addr;
1710 ANOFFSET (offs, SECT_OFF_BSS) = data_addr;
1712 objfile_relocate (symfile_objfile, offs);
1716 * Cisco version of section offsets:
1718 * Instead of having GDB query the target for the section offsets,
1719 * Cisco lets the target volunteer the information! It's also in
1720 * a different format, so here are the functions that will decode
1721 * a section offset packet from a Cisco target.
1725 * Function: remote_cisco_section_offsets
1727 * Returns: zero for success, non-zero for failure
1731 remote_cisco_section_offsets (text_addr, data_addr, bss_addr,
1732 text_offs, data_offs, bss_offs)
1736 bfd_signed_vma *text_offs;
1737 bfd_signed_vma *data_offs;
1738 bfd_signed_vma *bss_offs;
1740 bfd_vma text_base, data_base, bss_base;
1741 struct minimal_symbol *start;
1747 if (symfile_objfile == NULL)
1748 return -1; /* no can do nothin' */
1750 start = lookup_minimal_symbol ("_start", NULL, NULL);
1752 return -1; /* Can't find "_start" symbol */
1754 data_base = bss_base = 0;
1755 text_base = SYMBOL_VALUE_ADDRESS (start);
1757 abfd = symfile_objfile->obfd;
1758 for (sect = abfd->sections;
1762 p = (unsigned char *) bfd_get_section_name (abfd, sect);
1764 if (strcmp (p + len - 4, "data") == 0) /* ends in "data" */
1765 if (data_base == 0 ||
1766 data_base > bfd_get_section_vma (abfd, sect))
1767 data_base = bfd_get_section_vma (abfd, sect);
1768 if (strcmp (p + len - 3, "bss") == 0) /* ends in "bss" */
1769 if (bss_base == 0 ||
1770 bss_base > bfd_get_section_vma (abfd, sect))
1771 bss_base = bfd_get_section_vma (abfd, sect);
1773 *text_offs = text_addr - text_base;
1774 *data_offs = data_addr - data_base;
1775 *bss_offs = bss_addr - bss_base;
1780 sprintf (tmp, "VMA: text = 0x");
1781 sprintf_vma (tmp + strlen (tmp), text_addr);
1782 sprintf (tmp + strlen (tmp), " data = 0x");
1783 sprintf_vma (tmp + strlen (tmp), data_addr);
1784 sprintf (tmp + strlen (tmp), " bss = 0x");
1785 sprintf_vma (tmp + strlen (tmp), bss_addr);
1786 fprintf_filtered (gdb_stdlog, tmp);
1787 fprintf_filtered (gdb_stdlog,
1788 "Reloc offset: text = 0x%s data = 0x%s bss = 0x%s\n",
1789 paddr_nz (*text_offs),
1790 paddr_nz (*data_offs),
1791 paddr_nz (*bss_offs));
1798 * Function: remote_cisco_objfile_relocate
1800 * Relocate the symbol file for a remote target.
1804 remote_cisco_objfile_relocate (text_off, data_off, bss_off)
1805 bfd_signed_vma text_off;
1806 bfd_signed_vma data_off;
1807 bfd_signed_vma bss_off;
1809 struct section_offsets *offs;
1811 if (text_off != 0 || data_off != 0 || bss_off != 0)
1813 /* FIXME: This code assumes gdb-stabs.h is being used; it's
1814 broken for xcoff, dwarf, sdb-coff, etc. But there is no
1815 simple canonical representation for this stuff. */
1817 offs = (struct section_offsets *) alloca (SIZEOF_SECTION_OFFSETS);
1818 memcpy (offs, symfile_objfile->section_offsets, SIZEOF_SECTION_OFFSETS);
1820 ANOFFSET (offs, SECT_OFF_TEXT) = text_off;
1821 ANOFFSET (offs, SECT_OFF_DATA) = data_off;
1822 ANOFFSET (offs, SECT_OFF_BSS) = bss_off;
1824 /* First call the standard objfile_relocate. */
1825 objfile_relocate (symfile_objfile, offs);
1827 /* Now we need to fix up the section entries already attached to
1828 the exec target. These entries will control memory transfers
1829 from the exec file. */
1831 exec_set_section_offsets (text_off, data_off, bss_off);
1835 /* Stub for catch_errors. */
1838 remote_start_remote_dummy (dummy)
1841 start_remote (); /* Initialize gdb process mechanisms */
1846 remote_start_remote (dummy)
1849 immediate_quit = 1; /* Allow user to interrupt it */
1851 /* Ack any packet which the remote side has already sent. */
1852 SERIAL_WRITE (remote_desc, "+", 1);
1854 /* Let the stub know that we want it to return the thread. */
1857 inferior_pid = remote_current_thread (inferior_pid);
1859 get_offsets (); /* Get text, data & bss offsets */
1861 putpkt ("?"); /* initiate a query from remote machine */
1864 return remote_start_remote_dummy (dummy);
1867 /* Open a connection to a remote debugger.
1868 NAME is the filename used for communication. */
1871 remote_open (name, from_tty)
1875 remote_open_1 (name, from_tty, &remote_ops, 0);
1878 /* Just like remote_open, but with asynchronous support. */
1880 remote_async_open (name, from_tty)
1884 remote_async_open_1 (name, from_tty, &remote_async_ops, 0);
1887 /* Open a connection to a remote debugger using the extended
1888 remote gdb protocol. NAME is the filename used for communication. */
1891 extended_remote_open (name, from_tty)
1895 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */ );
1898 /* Just like extended_remote_open, but with asynchronous support. */
1900 extended_remote_async_open (name, from_tty)
1904 remote_async_open_1 (name, from_tty, &extended_async_remote_ops, 1 /*extended_p */ );
1907 /* Generic code for opening a connection to a remote target. */
1909 static DCACHE *remote_dcache;
1912 remote_open_1 (name, from_tty, target, extended_p)
1915 struct target_ops *target;
1919 error ("To open a remote debug connection, you need to specify what\n\
1920 serial device is attached to the remote system (e.g. /dev/ttya).");
1922 /* See FIXME above */
1923 wait_forever_enabled_p = 1;
1925 target_preopen (from_tty);
1927 unpush_target (target);
1929 remote_dcache = dcache_init (remote_read_bytes, remote_write_bytes);
1931 remote_desc = SERIAL_OPEN (name);
1933 perror_with_name (name);
1935 if (baud_rate != -1)
1937 if (SERIAL_SETBAUDRATE (remote_desc, baud_rate))
1939 SERIAL_CLOSE (remote_desc);
1940 perror_with_name (name);
1944 SERIAL_RAW (remote_desc);
1946 /* If there is something sitting in the buffer we might take it as a
1947 response to a command, which would be bad. */
1948 SERIAL_FLUSH_INPUT (remote_desc);
1952 puts_filtered ("Remote debugging using ");
1953 puts_filtered (name);
1954 puts_filtered ("\n");
1956 push_target (target); /* Switch to using remote target now */
1958 init_packet_config (&remote_protocol_P);
1959 init_packet_config (&remote_protocol_Z);
1961 general_thread = -2;
1962 continue_thread = -2;
1964 /* Force remote_write_bytes to check whether target supports
1965 binary downloading. */
1966 init_packet_config (&remote_protocol_binary_download);
1968 /* Without this, some commands which require an active target (such
1969 as kill) won't work. This variable serves (at least) double duty
1970 as both the pid of the target process (if it has such), and as a
1971 flag indicating that a target is active. These functions should
1972 be split out into seperate variables, especially since GDB will
1973 someday have a notion of debugging several processes. */
1975 inferior_pid = MAGIC_NULL_PID;
1976 /* Start the remote connection; if error (0), discard this target.
1977 In particular, if the user quits, be sure to discard it
1978 (we'd be in an inconsistent state otherwise). */
1979 if (!catch_errors (remote_start_remote, NULL,
1980 "Couldn't establish connection to remote target\n",
1989 /* tell the remote that we're using the extended protocol. */
1990 char *buf = alloca (PBUFSIZ);
1996 /* Just like remote_open but with asynchronous support. */
1998 remote_async_open_1 (name, from_tty, target, extended_p)
2001 struct target_ops *target;
2005 error ("To open a remote debug connection, you need to specify what\n\
2006 serial device is attached to the remote system (e.g. /dev/ttya).");
2008 target_preopen (from_tty);
2010 unpush_target (target);
2012 remote_dcache = dcache_init (remote_read_bytes, remote_write_bytes);
2014 remote_desc = SERIAL_OPEN (name);
2016 perror_with_name (name);
2018 if (baud_rate != -1)
2020 if (SERIAL_SETBAUDRATE (remote_desc, baud_rate))
2022 SERIAL_CLOSE (remote_desc);
2023 perror_with_name (name);
2027 SERIAL_RAW (remote_desc);
2029 /* If there is something sitting in the buffer we might take it as a
2030 response to a command, which would be bad. */
2031 SERIAL_FLUSH_INPUT (remote_desc);
2035 puts_filtered ("Remote debugging using ");
2036 puts_filtered (name);
2037 puts_filtered ("\n");
2040 push_target (target); /* Switch to using remote target now */
2042 init_packet_config (&remote_protocol_P);
2043 init_packet_config (&remote_protocol_Z);
2045 general_thread = -2;
2046 continue_thread = -2;
2048 /* Force remote_write_bytes to check whether target supports
2049 binary downloading. */
2050 init_packet_config (&remote_protocol_binary_download);
2052 /* Without this, some commands which require an active target (such
2053 as kill) won't work. This variable serves (at least) double duty
2054 as both the pid of the target process (if it has such), and as a
2055 flag indicating that a target is active. These functions should
2056 be split out into seperate variables, especially since GDB will
2057 someday have a notion of debugging several processes. */
2058 inferior_pid = MAGIC_NULL_PID;
2060 /* With this target we start out by owning the terminal. */
2061 remote_async_terminal_ours_p = 1;
2063 /* FIXME: cagney/1999-09-23: During the initial connection it is
2064 assumed that the target is already ready and able to respond to
2065 requests. Unfortunatly remote_start_remote() eventually calls
2066 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
2067 around this. Eventually a mechanism that allows
2068 wait_for_inferior() to expect/get timeouts will be
2070 wait_forever_enabled_p = 0;
2072 /* Start the remote connection; if error (0), discard this target.
2073 In particular, if the user quits, be sure to discard it
2074 (we'd be in an inconsistent state otherwise). */
2075 if (!catch_errors (remote_start_remote, NULL,
2076 "Couldn't establish connection to remote target\n",
2080 wait_forever_enabled_p = 1;
2084 wait_forever_enabled_p = 1;
2088 /* tell the remote that we're using the extended protocol. */
2089 char *buf = alloca (PBUFSIZ);
2095 /* This takes a program previously attached to and detaches it. After
2096 this is done, GDB can be used to debug some other program. We
2097 better not have left any breakpoints in the target program or it'll
2098 die when it hits one. */
2101 remote_detach (args, from_tty)
2105 char *buf = alloca (PBUFSIZ);
2108 error ("Argument given to \"detach\" when remotely debugging.");
2110 /* Tell the remote target to detach. */
2116 puts_filtered ("Ending remote debugging.\n");
2120 /* Same as remote_detach, but with async support. */
2122 remote_async_detach (args, from_tty)
2126 char *buf = alloca (PBUFSIZ);
2129 error ("Argument given to \"detach\" when remotely debugging.");
2131 /* Tell the remote target to detach. */
2135 /* Unregister the file descriptor from the event loop. */
2136 if (SERIAL_IS_ASYNC_P (remote_desc))
2137 SERIAL_ASYNC (remote_desc, NULL, 0);
2141 puts_filtered ("Ending remote debugging.\n");
2144 /* Convert hex digit A to a number. */
2150 if (a >= '0' && a <= '9')
2152 else if (a >= 'a' && a <= 'f')
2153 return a - 'a' + 10;
2154 else if (a >= 'A' && a <= 'F')
2155 return a - 'A' + 10;
2157 error ("Reply contains invalid hex digit %d", a);
2160 /* Convert number NIB to a hex digit. */
2169 return 'a' + nib - 10;
2172 /* Tell the remote machine to resume. */
2174 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
2176 static int last_sent_step;
2179 remote_resume (pid, step, siggnal)
2181 enum target_signal siggnal;
2183 char *buf = alloca (PBUFSIZ);
2186 set_thread (0, 0); /* run any thread */
2188 set_thread (pid, 0); /* run this thread */
2190 dcache_flush (remote_dcache);
2192 last_sent_signal = siggnal;
2193 last_sent_step = step;
2195 /* A hook for when we need to do something at the last moment before
2197 if (target_resume_hook)
2198 (*target_resume_hook) ();
2200 if (siggnal != TARGET_SIGNAL_0)
2202 buf[0] = step ? 'S' : 'C';
2203 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
2204 buf[2] = tohex ((int) siggnal & 0xf);
2208 strcpy (buf, step ? "s" : "c");
2213 /* Same as remote_resume, but with async support. */
2215 remote_async_resume (pid, step, siggnal)
2217 enum target_signal siggnal;
2219 char *buf = alloca (PBUFSIZ);
2222 set_thread (0, 0); /* run any thread */
2224 set_thread (pid, 0); /* run this thread */
2226 dcache_flush (remote_dcache);
2228 last_sent_signal = siggnal;
2229 last_sent_step = step;
2231 /* A hook for when we need to do something at the last moment before
2233 if (target_resume_hook)
2234 (*target_resume_hook) ();
2236 if (siggnal != TARGET_SIGNAL_0)
2238 buf[0] = step ? 'S' : 'C';
2239 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
2240 buf[2] = tohex ((int) siggnal & 0xf);
2244 strcpy (buf, step ? "s" : "c");
2246 /* We are about to start executing the inferior, let's register it
2247 with the event loop. NOTE: this is the one place where all the
2248 execution commands end up. We could alternatively do this in each
2249 of the execution commands in infcmd.c.*/
2250 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
2251 into infcmd.c in order to allow inferior function calls to work
2252 NOT asynchronously. */
2253 if (event_loop_p && SERIAL_CAN_ASYNC_P (remote_desc))
2254 target_async (inferior_event_handler, 0);
2255 /* Tell the world that the target is now executing. */
2256 /* FIXME: cagney/1999-09-23: Is it the targets responsibility to set
2257 this? Instead, should the client of target just assume (for
2258 async targets) that the target is going to start executing? Is
2259 this information already found in the continuation block? */
2260 if (SERIAL_IS_ASYNC_P (remote_desc))
2261 target_executing = 1;
2266 /* Set up the signal handler for SIGINT, while the target is
2267 executing, ovewriting the 'regular' SIGINT signal handler. */
2269 initialize_sigint_signal_handler ()
2271 sigint_remote_token =
2272 create_async_signal_handler (async_remote_interrupt, NULL);
2273 signal (SIGINT, handle_remote_sigint);
2276 /* Signal handler for SIGINT, while the target is executing. */
2278 handle_remote_sigint (sig)
2281 signal (sig, handle_remote_sigint_twice);
2282 sigint_remote_twice_token =
2283 create_async_signal_handler (async_remote_interrupt_twice, NULL);
2284 mark_async_signal_handler_wrapper (sigint_remote_token);
2287 /* Signal handler for SIGINT, installed after SIGINT has already been
2288 sent once. It will take effect the second time that the user sends
2291 handle_remote_sigint_twice (sig)
2294 signal (sig, handle_sigint);
2295 sigint_remote_twice_token =
2296 create_async_signal_handler (inferior_event_handler_wrapper, NULL);
2297 mark_async_signal_handler_wrapper (sigint_remote_twice_token);
2300 /* Perform the real interruption of the target execution, in response
2303 async_remote_interrupt (arg)
2304 gdb_client_data arg;
2307 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
2312 /* Perform interrupt, if the first attempt did not succeed. Just give
2313 up on the target alltogether. */
2315 async_remote_interrupt_twice (arg)
2316 gdb_client_data arg;
2319 fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
2320 /* Do something only if the target was not killed by the previous
2322 if (target_executing)
2325 signal (SIGINT, handle_remote_sigint);
2329 /* Reinstall the usual SIGINT handlers, after the target has
2332 cleanup_sigint_signal_handler (void *dummy)
2334 signal (SIGINT, handle_sigint);
2335 if (sigint_remote_twice_token)
2336 delete_async_signal_handler ((struct async_signal_handler **) & sigint_remote_twice_token);
2337 if (sigint_remote_token)
2338 delete_async_signal_handler ((struct async_signal_handler **) & sigint_remote_token);
2341 /* Send ^C to target to halt it. Target will respond, and send us a
2343 static void (*ofunc) PARAMS ((int));
2345 /* The command line interface's stop routine. This function is installed
2346 as a signal handler for SIGINT. The first time a user requests a
2347 stop, we call remote_stop to send a break or ^C. If there is no
2348 response from the target (it didn't stop when the user requested it),
2349 we ask the user if he'd like to detach from the target. */
2351 remote_interrupt (signo)
2354 /* If this doesn't work, try more severe steps. */
2355 signal (signo, remote_interrupt_twice);
2358 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
2363 /* The user typed ^C twice. */
2366 remote_interrupt_twice (signo)
2369 signal (signo, ofunc);
2371 signal (signo, remote_interrupt);
2374 /* This is the generic stop called via the target vector. When a target
2375 interrupt is requested, either by the command line or the GUI, we
2376 will eventually end up here. */
2380 /* Send a break or a ^C, depending on user preference. */
2382 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
2385 SERIAL_SEND_BREAK (remote_desc);
2387 SERIAL_WRITE (remote_desc, "\003", 1);
2390 /* Ask the user what to do when an interrupt is received. */
2395 target_terminal_ours ();
2397 if (query ("Interrupted while waiting for the program.\n\
2398 Give up (and stop debugging it)? "))
2400 target_mourn_inferior ();
2401 return_to_top_level (RETURN_QUIT);
2404 target_terminal_inferior ();
2407 /* Enable/disable target terminal ownership. Most targets can use
2408 terminal groups to control terminal ownership. Remote targets are
2409 different in that explicit transfer of ownership to/from GDB/target
2413 remote_async_terminal_inferior (void)
2415 /* FIXME: cagney/1999-09-27: Shouldn't need to test for
2416 sync_execution here. This function should only be called when
2417 GDB is resuming the inferior in the forground. A background
2418 resume (``run&'') should leave GDB in control of the terminal and
2419 consequently should not call this code. */
2420 if (!sync_execution)
2422 /* FIXME: cagney/1999-09-27: Closely related to the above. Make
2423 calls target_terminal_*() idenpotent. The event-loop GDB talking
2424 to an asynchronous target with a synchronous command calls this
2425 function from both event-top.c and infrun.c/infcmd.c. Once GDB
2426 stops trying to transfer the terminal to the target when it
2427 shouldn't this guard can go away. */
2428 if (!remote_async_terminal_ours_p)
2430 delete_file_handler (input_fd);
2431 remote_async_terminal_ours_p = 0;
2432 initialize_sigint_signal_handler ();
2433 /* NOTE: At this point we could also register our selves as the
2434 recipient of all input. Any characters typed could then be
2435 passed on down to the target. */
2439 remote_async_terminal_ours (void)
2441 /* See FIXME in remote_async_terminal_inferior. */
2442 if (!sync_execution)
2444 /* See FIXME in remote_async_terminal_inferior. */
2445 if (remote_async_terminal_ours_p)
2447 cleanup_sigint_signal_handler (NULL);
2448 add_file_handler (input_fd, stdin_event_handler, 0);
2449 remote_async_terminal_ours_p = 1;
2452 /* If nonzero, ignore the next kill. */
2457 remote_console_output (char *msg)
2461 for (p = msg; p[0] && p[1]; p += 2)
2464 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
2467 fputs_unfiltered (tb, gdb_stdtarg);
2469 gdb_flush (gdb_stdtarg);
2472 /* Wait until the remote machine stops, then return,
2473 storing status in STATUS just as `wait' would.
2474 Returns "pid", which in the case of a multi-threaded
2475 remote OS, is the thread-id. */
2478 remote_wait (pid, status)
2480 struct target_waitstatus *status;
2482 unsigned char *buf = alloca (PBUFSIZ);
2483 int thread_num = -1;
2485 status->kind = TARGET_WAITKIND_EXITED;
2486 status->value.integer = 0;
2492 ofunc = signal (SIGINT, remote_interrupt);
2493 getpkt ((char *) buf, 1);
2494 signal (SIGINT, ofunc);
2496 /* This is a hook for when we need to do something (perhaps the
2497 collection of trace data) every time the target stops. */
2498 if (target_wait_loop_hook)
2499 (*target_wait_loop_hook) ();
2503 case 'E': /* Error of some sort */
2504 warning ("Remote failure reply: %s", buf);
2506 case 'T': /* Status with PC, SP, FP, ... */
2510 char regs[MAX_REGISTER_RAW_SIZE];
2512 /* Expedited reply, containing Signal, {regno, reg} repeat */
2513 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
2515 n... = register number
2516 r... = register contents
2518 p = &buf[3]; /* after Txx */
2525 /* Read the register number */
2526 regno = strtol ((const char *) p, &p_temp, 16);
2527 p1 = (unsigned char *) p_temp;
2529 if (p1 == p) /* No register number present here */
2531 p1 = (unsigned char *) strchr ((const char *) p, ':');
2533 warning ("Malformed packet(a) (missing colon): %s\n\
2536 if (strncmp ((const char *) p, "thread", p1 - p) == 0)
2538 p_temp = unpack_varlen_hex (++p1, &thread_num);
2539 record_currthread (thread_num);
2540 p = (unsigned char *) p_temp;
2548 warning ("Malformed packet(b) (missing colon): %s\n\
2552 if (regno >= NUM_REGS)
2553 warning ("Remote sent bad register number %ld: %s\n\
2557 for (i = 0; i < REGISTER_RAW_SIZE (regno); i++)
2559 if (p[0] == 0 || p[1] == 0)
2560 warning ("Remote reply is too short: %s", buf);
2561 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
2564 supply_register (regno, regs);
2569 warning ("Remote register badly formatted: %s", buf);
2570 warning (" here: %s", p);
2575 case 'S': /* Old style status, just signal only */
2576 status->kind = TARGET_WAITKIND_STOPPED;
2577 status->value.sig = (enum target_signal)
2578 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
2582 /* Export Cisco kernel mode as a convenience variable
2583 (so that it can be used in the GDB prompt if desired). */
2585 if (cisco_kernel_mode == 1)
2586 set_internalvar (lookup_internalvar ("cisco_kernel_mode"),
2587 value_from_string ("PDEBUG-"));
2588 cisco_kernel_mode = 0;
2589 thread_num = strtol ((const char *) &buf[4], NULL, 16);
2590 record_currthread (thread_num);
2592 else if (buf[3] == 'k')
2594 /* Export Cisco kernel mode as a convenience variable
2595 (so that it can be used in the GDB prompt if desired). */
2597 if (cisco_kernel_mode == 1)
2598 set_internalvar (lookup_internalvar ("cisco_kernel_mode"),
2599 value_from_string ("KDEBUG-"));
2600 cisco_kernel_mode = 1;
2603 case 'N': /* Cisco special: status and offsets */
2605 bfd_vma text_addr, data_addr, bss_addr;
2606 bfd_signed_vma text_off, data_off, bss_off;
2609 status->kind = TARGET_WAITKIND_STOPPED;
2610 status->value.sig = (enum target_signal)
2611 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
2613 if (symfile_objfile == NULL)
2615 warning ("Relocation packet received with no symbol file. \
2620 /* Relocate object file. Buffer format is NAATT;DD;BB
2621 * where AA is the signal number, TT is the new text
2622 * address, DD * is the new data address, and BB is the
2623 * new bss address. */
2626 text_addr = strtoul (p, (char **) &p1, 16);
2627 if (p1 == p || *p1 != ';')
2628 warning ("Malformed relocation packet: Packet '%s'", buf);
2630 data_addr = strtoul (p, (char **) &p1, 16);
2631 if (p1 == p || *p1 != ';')
2632 warning ("Malformed relocation packet: Packet '%s'", buf);
2634 bss_addr = strtoul (p, (char **) &p1, 16);
2636 warning ("Malformed relocation packet: Packet '%s'", buf);
2638 if (remote_cisco_section_offsets (text_addr, data_addr, bss_addr,
2639 &text_off, &data_off, &bss_off)
2641 if (text_off != 0 || data_off != 0 || bss_off != 0)
2642 remote_cisco_objfile_relocate (text_off, data_off, bss_off);
2646 case 'W': /* Target exited */
2648 /* The remote process exited. */
2649 status->kind = TARGET_WAITKIND_EXITED;
2650 status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
2654 status->kind = TARGET_WAITKIND_SIGNALLED;
2655 status->value.sig = (enum target_signal)
2656 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
2660 case 'O': /* Console output */
2661 remote_console_output (buf + 1);
2664 if (last_sent_signal != TARGET_SIGNAL_0)
2666 /* Zero length reply means that we tried 'S' or 'C' and
2667 the remote system doesn't support it. */
2668 target_terminal_ours_for_output ();
2670 ("Can't send signals to this remote system. %s not sent.\n",
2671 target_signal_to_name (last_sent_signal));
2672 last_sent_signal = TARGET_SIGNAL_0;
2673 target_terminal_inferior ();
2675 strcpy ((char *) buf, last_sent_step ? "s" : "c");
2676 putpkt ((char *) buf);
2679 /* else fallthrough */
2681 warning ("Invalid remote reply: %s", buf);
2686 if (thread_num != -1)
2690 return inferior_pid;
2693 /* Async version of remote_wait. */
2695 remote_async_wait (pid, status)
2697 struct target_waitstatus *status;
2699 unsigned char *buf = alloca (PBUFSIZ);
2700 int thread_num = -1;
2702 status->kind = TARGET_WAITKIND_EXITED;
2703 status->value.integer = 0;
2709 if (!SERIAL_IS_ASYNC_P (remote_desc))
2710 ofunc = signal (SIGINT, remote_interrupt);
2711 /* FIXME: cagney/1999-09-27: If we're in async mode we should
2712 _never_ wait for ever -> test on target_is_async_p().
2713 However, before we do that we need to ensure that the caller
2714 knows how to take the target into/out of async mode. */
2715 getpkt ((char *) buf, wait_forever_enabled_p);
2716 if (!SERIAL_IS_ASYNC_P (remote_desc))
2717 signal (SIGINT, ofunc);
2719 /* This is a hook for when we need to do something (perhaps the
2720 collection of trace data) every time the target stops. */
2721 if (target_wait_loop_hook)
2722 (*target_wait_loop_hook) ();
2726 case 'E': /* Error of some sort */
2727 warning ("Remote failure reply: %s", buf);
2729 case 'T': /* Status with PC, SP, FP, ... */
2733 char regs[MAX_REGISTER_RAW_SIZE];
2735 /* Expedited reply, containing Signal, {regno, reg} repeat */
2736 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
2738 n... = register number
2739 r... = register contents
2741 p = &buf[3]; /* after Txx */
2748 /* Read the register number */
2749 regno = strtol ((const char *) p, &p_temp, 16);
2750 p1 = (unsigned char *) p_temp;
2752 if (p1 == p) /* No register number present here */
2754 p1 = (unsigned char *) strchr ((const char *) p, ':');
2756 warning ("Malformed packet(a) (missing colon): %s\n\
2759 if (strncmp ((const char *) p, "thread", p1 - p) == 0)
2761 p_temp = unpack_varlen_hex (++p1, &thread_num);
2762 record_currthread (thread_num);
2763 p = (unsigned char *) p_temp;
2771 warning ("Malformed packet(b) (missing colon): %s\n\
2775 if (regno >= NUM_REGS)
2776 warning ("Remote sent bad register number %ld: %s\n\
2780 for (i = 0; i < REGISTER_RAW_SIZE (regno); i++)
2782 if (p[0] == 0 || p[1] == 0)
2783 warning ("Remote reply is too short: %s", buf);
2784 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
2787 supply_register (regno, regs);
2792 warning ("Remote register badly formatted: %s", buf);
2793 warning (" here: %s", p);
2798 case 'S': /* Old style status, just signal only */
2799 status->kind = TARGET_WAITKIND_STOPPED;
2800 status->value.sig = (enum target_signal)
2801 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
2805 /* Export Cisco kernel mode as a convenience variable
2806 (so that it can be used in the GDB prompt if desired). */
2808 if (cisco_kernel_mode == 1)
2809 set_internalvar (lookup_internalvar ("cisco_kernel_mode"),
2810 value_from_string ("PDEBUG-"));
2811 cisco_kernel_mode = 0;
2812 thread_num = strtol ((const char *) &buf[4], NULL, 16);
2813 record_currthread (thread_num);
2815 else if (buf[3] == 'k')
2817 /* Export Cisco kernel mode as a convenience variable
2818 (so that it can be used in the GDB prompt if desired). */
2820 if (cisco_kernel_mode == 1)
2821 set_internalvar (lookup_internalvar ("cisco_kernel_mode"),
2822 value_from_string ("KDEBUG-"));
2823 cisco_kernel_mode = 1;
2826 case 'N': /* Cisco special: status and offsets */
2828 bfd_vma text_addr, data_addr, bss_addr;
2829 bfd_signed_vma text_off, data_off, bss_off;
2832 status->kind = TARGET_WAITKIND_STOPPED;
2833 status->value.sig = (enum target_signal)
2834 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
2836 if (symfile_objfile == NULL)
2838 warning ("Relocation packet recieved with no symbol file. \
2843 /* Relocate object file. Buffer format is NAATT;DD;BB
2844 * where AA is the signal number, TT is the new text
2845 * address, DD * is the new data address, and BB is the
2846 * new bss address. */
2849 text_addr = strtoul (p, (char **) &p1, 16);
2850 if (p1 == p || *p1 != ';')
2851 warning ("Malformed relocation packet: Packet '%s'", buf);
2853 data_addr = strtoul (p, (char **) &p1, 16);
2854 if (p1 == p || *p1 != ';')
2855 warning ("Malformed relocation packet: Packet '%s'", buf);
2857 bss_addr = strtoul (p, (char **) &p1, 16);
2859 warning ("Malformed relocation packet: Packet '%s'", buf);
2861 if (remote_cisco_section_offsets (text_addr, data_addr, bss_addr,
2862 &text_off, &data_off, &bss_off)
2864 if (text_off != 0 || data_off != 0 || bss_off != 0)
2865 remote_cisco_objfile_relocate (text_off, data_off, bss_off);
2869 case 'W': /* Target exited */
2871 /* The remote process exited. */
2872 status->kind = TARGET_WAITKIND_EXITED;
2873 status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
2877 status->kind = TARGET_WAITKIND_SIGNALLED;
2878 status->value.sig = (enum target_signal)
2879 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
2883 case 'O': /* Console output */
2884 remote_console_output (buf + 1);
2887 if (last_sent_signal != TARGET_SIGNAL_0)
2889 /* Zero length reply means that we tried 'S' or 'C' and
2890 the remote system doesn't support it. */
2891 target_terminal_ours_for_output ();
2893 ("Can't send signals to this remote system. %s not sent.\n",
2894 target_signal_to_name (last_sent_signal));
2895 last_sent_signal = TARGET_SIGNAL_0;
2896 target_terminal_inferior ();
2898 strcpy ((char *) buf, last_sent_step ? "s" : "c");
2899 putpkt ((char *) buf);
2902 /* else fallthrough */
2904 warning ("Invalid remote reply: %s", buf);
2909 if (thread_num != -1)
2913 return inferior_pid;
2916 /* Number of bytes of registers this stub implements. */
2918 static int register_bytes_found;
2920 /* Read the remote registers into the block REGS. */
2921 /* Currently we just read all the registers, so we don't use regno. */
2925 remote_fetch_registers (regno)
2928 char *buf = alloca (PBUFSIZ);
2931 char regs[REGISTER_BYTES];
2933 set_thread (inferior_pid, 1);
2938 /* Save the size of the packet sent to us by the target. Its used
2939 as a heuristic when determining the max size of packets that the
2940 target can safely receive. */
2941 if (actual_register_packet_size == 0)
2942 actual_register_packet_size = strlen (buf);
2944 /* Unimplemented registers read as all bits zero. */
2945 memset (regs, 0, REGISTER_BYTES);
2947 /* We can get out of synch in various cases. If the first character
2948 in the buffer is not a hex character, assume that has happened
2949 and try to fetch another packet to read. */
2950 while ((buf[0] < '0' || buf[0] > '9')
2951 && (buf[0] < 'a' || buf[0] > 'f')
2952 && buf[0] != 'x') /* New: unavailable register value */
2955 fprintf_unfiltered (gdb_stdlog,
2956 "Bad register packet; fetching a new packet\n");
2960 /* Reply describes registers byte by byte, each byte encoded as two
2961 hex characters. Suck them all up, then supply them to the
2962 register cacheing/storage mechanism. */
2965 for (i = 0; i < REGISTER_BYTES; i++)
2971 warning ("Remote reply is of odd length: %s", buf);
2972 /* Don't change register_bytes_found in this case, and don't
2973 print a second warning. */
2976 if (p[0] == 'x' && p[1] == 'x')
2977 regs[i] = 0; /* 'x' */
2979 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
2983 if (i != register_bytes_found)
2985 register_bytes_found = i;
2986 #ifdef REGISTER_BYTES_OK
2987 if (!REGISTER_BYTES_OK (i))
2988 warning ("Remote reply is too short: %s", buf);
2993 for (i = 0; i < NUM_REGS; i++)
2995 supply_register (i, ®s[REGISTER_BYTE (i)]);
2996 if (buf[REGISTER_BYTE (i) * 2] == 'x')
2997 register_valid[i] = -1; /* register value not available */
3001 /* Prepare to store registers. Since we may send them all (using a
3002 'G' request), we have to read out the ones we don't want to change
3006 remote_prepare_to_store ()
3008 /* Make sure the entire registers array is valid. */
3009 switch (remote_protocol_P.support)
3011 case PACKET_DISABLE:
3012 case PACKET_SUPPORT_UNKNOWN:
3013 read_register_bytes (0, (char *) NULL, REGISTER_BYTES);
3020 /* Helper: Attempt to store REGNO using the P packet. Return fail IFF
3021 packet was not recognized. */
3024 store_register_using_P (regno)
3027 /* Try storing a single register. */
3028 char *buf = alloca (PBUFSIZ);
3033 sprintf (buf, "P%x=", regno);
3034 p = buf + strlen (buf);
3035 regp = ®isters[REGISTER_BYTE (regno)];
3036 for (i = 0; i < REGISTER_RAW_SIZE (regno); ++i)
3038 *p++ = tohex ((regp[i] >> 4) & 0xf);
3039 *p++ = tohex (regp[i] & 0xf);
3044 return buf[0] != '\0';
3048 /* Store register REGNO, or all registers if REGNO == -1, from the contents
3049 of REGISTERS. FIXME: ignores errors. */
3052 remote_store_registers (regno)
3055 char *buf = alloca (PBUFSIZ);
3059 set_thread (inferior_pid, 1);
3063 switch (remote_protocol_P.support)
3065 case PACKET_DISABLE:
3068 if (store_register_using_P (regno))
3071 error ("Protocol error: P packet not recognized by stub");
3072 case PACKET_SUPPORT_UNKNOWN:
3073 if (store_register_using_P (regno))
3075 /* The stub recognized the 'P' packet. Remember this. */
3076 remote_protocol_P.support = PACKET_ENABLE;
3081 /* The stub does not support the 'P' packet. Use 'G'
3082 instead, and don't try using 'P' in the future (it
3083 will just waste our time). */
3084 remote_protocol_P.support = PACKET_DISABLE;
3092 /* Command describes registers byte by byte,
3093 each byte encoded as two hex characters. */
3096 /* remote_prepare_to_store insures that register_bytes_found gets set. */
3097 for (i = 0; i < register_bytes_found; i++)
3099 *p++ = tohex ((registers[i] >> 4) & 0xf);
3100 *p++ = tohex (registers[i] & 0xf);
3107 /* Use of the data cache *used* to be disabled because it loses for looking
3108 at and changing hardware I/O ports and the like. Accepting `volatile'
3109 would perhaps be one way to fix it. Another idea would be to use the
3110 executable file for the text segment (for all SEC_CODE sections?
3111 For all SEC_READONLY sections?). This has problems if you want to
3112 actually see what the memory contains (e.g. self-modifying code,
3113 clobbered memory, user downloaded the wrong thing).
3115 Because it speeds so much up, it's now enabled, if you're playing
3116 with registers you turn it of (set remotecache 0). */
3118 /* Read a word from remote address ADDR and return it.
3119 This goes through the data cache. */
3123 remote_fetch_word (addr)
3126 return dcache_fetch (remote_dcache, addr);
3129 /* Write a word WORD into remote address ADDR.
3130 This goes through the data cache. */
3133 remote_store_word (addr, word)
3137 dcache_poke (remote_dcache, addr, word);
3139 #endif /* 0 (unused?) */
3143 /* Return the number of hex digits in num. */
3151 for (i = 0; num != 0; i++)
3157 /* Set BUF to the minimum number of hex digits representing NUM. */
3160 hexnumstr (buf, num)
3164 int len = hexnumlen (num);
3165 return hexnumnstr (buf, num, len);
3169 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
3172 hexnumnstr (buf, num, width)
3181 for (i = width - 1; i >= 0; i--)
3183 buf[i] = "0123456789abcdef"[(num & 0xf)];
3190 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
3193 remote_address_masked (addr)
3196 if (remote_address_size > 0
3197 && remote_address_size < (sizeof (ULONGEST) * 8))
3199 /* Only create a mask when that mask can safely be constructed
3200 in a ULONGEST variable. */
3202 mask = (mask << remote_address_size) - 1;
3208 /* Determine whether the remote target supports binary downloading.
3209 This is accomplished by sending a no-op memory write of zero length
3210 to the target at the specified address. It does not suffice to send
3211 the whole packet, since many stubs strip the eighth bit and subsequently
3212 compute a wrong checksum, which causes real havoc with remote_write_bytes.
3214 NOTE: This can still lose if the serial line is not eight-bit
3215 clean. In cases like this, the user should clear "remote
3219 check_binary_download (addr)
3222 switch (remote_protocol_binary_download.support)
3224 case PACKET_DISABLE:
3228 case PACKET_SUPPORT_UNKNOWN:
3230 char *buf = alloca (PBUFSIZ);
3235 p += hexnumstr (p, (ULONGEST) addr);
3237 p += hexnumstr (p, (ULONGEST) 0);
3241 putpkt_binary (buf, (int) (p - buf));
3247 fprintf_unfiltered (gdb_stdlog,
3248 "binary downloading NOT suppported by target\n");
3249 remote_protocol_binary_download.support = PACKET_DISABLE;
3254 fprintf_unfiltered (gdb_stdlog,
3255 "binary downloading suppported by target\n");
3256 remote_protocol_binary_download.support = PACKET_ENABLE;
3263 /* Write memory data directly to the remote machine.
3264 This does not inform the data cache; the data cache uses this.
3265 MEMADDR is the address in the remote memory space.
3266 MYADDR is the address of the buffer in our space.
3267 LEN is the number of bytes.
3269 Returns number of bytes transferred, or 0 (setting errno) for
3270 error. Only transfer a single packet. */
3273 remote_write_bytes (CORE_ADDR memaddr, char *myaddr, int len)
3276 int max_buf_size; /* Max size of packet output buffer */
3278 unsigned char *plen;
3283 /* Verify that the target can support a binary download */
3284 check_binary_download (memaddr);
3286 /* Determine the max packet size. */
3287 max_buf_size = get_memory_write_packet_size ();
3288 buf = alloca (max_buf_size + 1);
3290 /* Subtract header overhead from max payload size - $M<memaddr>,<len>:#nn */
3291 max_buf_size -= 2 + hexnumlen (memaddr + len - 1) + 1 + hexnumlen (len) + 4;
3293 /* construct "M"<memaddr>","<len>":" */
3294 /* sprintf (buf, "M%lx,%x:", (unsigned long) memaddr, todo); */
3297 /* Append [XM]. Compute a best guess of the number of bytes
3298 actually transfered. */
3299 switch (remote_protocol_binary_download.support)
3303 /* Best guess at number of bytes that will fit. */
3304 todo = min (len, max_buf_size);
3306 case PACKET_DISABLE:
3308 /* num bytes that will fit */
3309 todo = min (len, max_buf_size / 2);
3311 case PACKET_SUPPORT_UNKNOWN:
3312 internal_error ("remote_write_bytes: bad switch");
3315 /* Append <memaddr> */
3316 memaddr = remote_address_masked (memaddr);
3317 p += hexnumstr (p, (ULONGEST) memaddr);
3320 /* Append <len>. Retain the location/size of <len>. It may
3321 need to be adjusted once the packet body has been created. */
3323 plenlen = hexnumstr (p, (ULONGEST) todo);
3328 /* Append the packet body. */
3329 switch (remote_protocol_binary_download.support)
3332 /* Binary mode. Send target system values byte by byte, in
3333 increasing byte addresses. Only escape certain critical
3336 (nr_bytes < todo) && (p - buf) < (max_buf_size - 2);
3339 switch (myaddr[nr_bytes] & 0xff)
3344 /* These must be escaped */
3346 *p++ = (myaddr[nr_bytes] & 0xff) ^ 0x20;
3349 *p++ = myaddr[nr_bytes] & 0xff;
3353 if (nr_bytes < todo)
3355 /* Escape chars have filled up the buffer prematurely,
3356 and we have actually sent fewer bytes than planned.
3357 Fix-up the length field of the packet. Use the same
3358 number of characters as before. */
3360 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
3361 *plen = ':'; /* overwrite \0 from hexnumnstr() */
3364 case PACKET_DISABLE:
3365 /* Normal mode: Send target system values byte by byte, in
3366 increasing byte addresses. Each byte is encoded as a two hex
3368 for (nr_bytes = 0; nr_bytes < todo; nr_bytes++)
3370 *p++ = tohex ((myaddr[nr_bytes] >> 4) & 0xf);
3371 *p++ = tohex (myaddr[nr_bytes] & 0xf);
3375 case PACKET_SUPPORT_UNKNOWN:
3376 internal_error ("remote_write_bytes: bad switch");
3379 putpkt_binary (buf, (int) (p - buf));
3384 /* There is no correspondance between what the remote protocol
3385 uses for errors and errno codes. We would like a cleaner way
3386 of representing errors (big enough to include errno codes,
3387 bfd_error codes, and others). But for now just return EIO. */
3392 /* Return NR_BYTES, not TODO, in case escape chars caused us to send fewer
3393 bytes than we'd planned. */
3397 /* Read memory data directly from the remote machine.
3398 This does not use the data cache; the data cache uses this.
3399 MEMADDR is the address in the remote memory space.
3400 MYADDR is the address of the buffer in our space.
3401 LEN is the number of bytes.
3403 Returns number of bytes transferred, or 0 for error. */
3405 /* NOTE: cagney/1999-10-18: This function (and its siblings in other
3406 remote targets) shouldn't attempt to read the entire buffer.
3407 Instead it should read a single packet worth of data and then
3408 return the byte size of that packet to the caller. The caller (its
3409 caller and its callers caller ;-) already contains code for
3410 handling partial reads. */
3413 remote_read_bytes (memaddr, myaddr, len)
3419 int max_buf_size; /* Max size of packet output buffer */
3422 /* Create a buffer big enough for this packet. */
3423 max_buf_size = get_memory_read_packet_size ();
3424 buf = alloca (max_buf_size);
3433 todo = min (len, max_buf_size / 2); /* num bytes that will fit */
3435 /* construct "m"<memaddr>","<len>" */
3436 /* sprintf (buf, "m%lx,%x", (unsigned long) memaddr, todo); */
3437 memaddr = remote_address_masked (memaddr);
3440 p += hexnumstr (p, (ULONGEST) memaddr);
3442 p += hexnumstr (p, (ULONGEST) todo);
3450 /* There is no correspondance between what the remote protocol uses
3451 for errors and errno codes. We would like a cleaner way of
3452 representing errors (big enough to include errno codes, bfd_error
3453 codes, and others). But for now just return EIO. */
3458 /* Reply describes memory byte by byte,
3459 each byte encoded as two hex characters. */
3462 for (i = 0; i < todo; i++)
3464 if (p[0] == 0 || p[1] == 0)
3465 /* Reply is short. This means that we were able to read
3466 only part of what we wanted to. */
3467 return i + (origlen - len);
3468 myaddr[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
3478 /* Read or write LEN bytes from inferior memory at MEMADDR,
3479 transferring to or from debugger address BUFFER. Write to inferior if
3480 SHOULD_WRITE is nonzero. Returns length of data written or read; 0
3483 #ifndef REMOTE_TRANSLATE_XFER_ADDRESS
3484 #define REMOTE_TRANSLATE_XFER_ADDRESS(MEM_ADDR, MEM_LEN, TARG_ADDR, TARG_LEN) \
3485 (*(TARG_ADDR) = (MEM_ADDR), *(TARG_LEN) = (MEM_LEN))
3490 remote_xfer_memory (mem_addr, buffer, mem_len, should_write, target)
3495 struct target_ops *target; /* ignored */
3497 CORE_ADDR targ_addr;
3499 REMOTE_TRANSLATE_XFER_ADDRESS (mem_addr, mem_len, &targ_addr, &targ_len);
3503 return dcache_xfer_memory (remote_dcache, targ_addr, buffer,
3504 targ_len, should_write);
3509 /* Enable after 4.12. */
3512 remote_search (len, data, mask, startaddr, increment, lorange, hirange
3513 addr_found, data_found)
3517 CORE_ADDR startaddr;
3521 CORE_ADDR *addr_found;
3524 if (increment == -4 && len == 4)
3526 long mask_long, data_long;
3527 long data_found_long;
3528 CORE_ADDR addr_we_found;
3529 char *buf = alloca (PBUFSIZ);
3530 long returned_long[2];
3533 mask_long = extract_unsigned_integer (mask, len);
3534 data_long = extract_unsigned_integer (data, len);
3535 sprintf (buf, "t%x:%x,%x", startaddr, data_long, mask_long);
3540 /* The stub doesn't support the 't' request. We might want to
3541 remember this fact, but on the other hand the stub could be
3542 switched on us. Maybe we should remember it only until
3543 the next "target remote". */
3544 generic_search (len, data, mask, startaddr, increment, lorange,
3545 hirange, addr_found, data_found);
3550 /* There is no correspondance between what the remote protocol uses
3551 for errors and errno codes. We would like a cleaner way of
3552 representing errors (big enough to include errno codes, bfd_error
3553 codes, and others). But for now just use EIO. */
3554 memory_error (EIO, startaddr);
3557 while (*p != '\0' && *p != ',')
3558 addr_we_found = (addr_we_found << 4) + fromhex (*p++);
3560 error ("Protocol error: short return for search");
3562 data_found_long = 0;
3563 while (*p != '\0' && *p != ',')
3564 data_found_long = (data_found_long << 4) + fromhex (*p++);
3565 /* Ignore anything after this comma, for future extensions. */
3567 if (addr_we_found < lorange || addr_we_found >= hirange)
3573 *addr_found = addr_we_found;
3574 *data_found = store_unsigned_integer (data_we_found, len);
3577 generic_search (len, data, mask, startaddr, increment, lorange,
3578 hirange, addr_found, data_found);
3583 remote_files_info (ignore)
3584 struct target_ops *ignore;
3586 puts_filtered ("Debugging a target over a serial line.\n");
3589 /* Stuff for dealing with the packets which are part of this protocol.
3590 See comment at top of file for details. */
3592 /* Read a single character from the remote end, masking it down to 7 bits. */
3600 ch = SERIAL_READCHAR (remote_desc, timeout);
3605 switch ((enum serial_rc) ch)
3608 target_mourn_inferior ();
3609 error ("Remote connection closed");
3612 perror_with_name ("Remote communication error");
3614 case SERIAL_TIMEOUT:
3620 /* Send the command in BUF to the remote machine, and read the reply
3621 into BUF. Report an error if we get an error reply. */
3631 error ("Remote failure reply: %s", buf);
3634 /* Display a null-terminated packet on stdout, for debugging, using C
3641 puts_filtered ("\"");
3642 fputstr_filtered (buf, '"', gdb_stdout);
3643 puts_filtered ("\"");
3650 return putpkt_binary (buf, strlen (buf));
3653 /* Send a packet to the remote machine, with error checking. The data
3654 of the packet is in BUF. The string in BUF can be at most PBUFSIZ - 5
3655 to account for the $, # and checksum, and for a possible /0 if we are
3656 debugging (remote_debug) and want to print the sent packet as a string */
3659 putpkt_binary (buf, cnt)
3664 unsigned char csum = 0;
3665 char *buf2 = alloca (cnt + 6);
3666 char *junkbuf = alloca (PBUFSIZ);
3672 /* Copy the packet into buffer BUF2, encapsulating it
3673 and giving it a checksum. */
3678 for (i = 0; i < cnt; i++)
3684 *p++ = tohex ((csum >> 4) & 0xf);
3685 *p++ = tohex (csum & 0xf);
3687 /* Send it over and over until we get a positive ack. */
3691 int started_error_output = 0;
3696 fprintf_unfiltered (gdb_stdlog, "Sending packet: ");
3697 fputstrn_unfiltered (buf2, p - buf2, 0, gdb_stdlog);
3698 fprintf_unfiltered (gdb_stdlog, "...");
3699 gdb_flush (gdb_stdlog);
3701 if (SERIAL_WRITE (remote_desc, buf2, p - buf2))
3702 perror_with_name ("putpkt: write failed");
3704 /* read until either a timeout occurs (-2) or '+' is read */
3707 ch = readchar (remote_timeout);
3714 case SERIAL_TIMEOUT:
3716 if (started_error_output)
3718 putchar_unfiltered ('\n');
3719 started_error_output = 0;
3728 fprintf_unfiltered (gdb_stdlog, "Ack\n");
3730 case SERIAL_TIMEOUT:
3734 break; /* Retransmit buffer */
3737 /* It's probably an old response, and we're out of sync.
3738 Just gobble up the packet and ignore it. */
3739 getpkt (junkbuf, 0);
3740 continue; /* Now, go look for + */
3745 if (!started_error_output)
3747 started_error_output = 1;
3748 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
3750 fputc_unfiltered (ch & 0177, gdb_stdlog);
3754 break; /* Here to retransmit */
3758 /* This is wrong. If doing a long backtrace, the user should be
3759 able to get out next time we call QUIT, without anything as
3760 violent as interrupt_query. If we want to provide a way out of
3761 here without getting to the next QUIT, it should be based on
3762 hitting ^C twice as in remote_wait. */
3772 static int remote_cisco_mode;
3774 /* Come here after finding the start of the frame. Collect the rest
3775 into BUF, verifying the checksum, length, and handling run-length
3776 compression. Returns 0 on any error, 1 on success. */
3791 c = readchar (remote_timeout);
3795 case SERIAL_TIMEOUT:
3797 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
3801 fputs_filtered ("Saw new packet start in middle of old one\n",
3803 return 0; /* Start a new packet, count retries */
3806 unsigned char pktcsum;
3810 pktcsum = fromhex (readchar (remote_timeout)) << 4;
3811 pktcsum |= fromhex (readchar (remote_timeout));
3813 if (csum == pktcsum)
3818 fprintf_filtered (gdb_stdlog,
3819 "Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
3821 fputs_filtered (buf, gdb_stdlog);
3822 fputs_filtered ("\n", gdb_stdlog);
3826 case '*': /* Run length encoding */
3831 if (remote_cisco_mode == 0)
3833 c = readchar (remote_timeout);
3835 repeat = c - ' ' + 3; /* Compute repeat count */
3839 /* Cisco's run-length encoding variant uses two
3840 hex chars to represent the repeat count. */
3842 c = readchar (remote_timeout);
3844 repeat = fromhex (c) << 4;
3845 c = readchar (remote_timeout);
3847 repeat += fromhex (c);
3850 if (repeat > 0 && repeat <= 255
3851 && bp + repeat - 1 < buf + PBUFSIZ - 1)
3853 memset (bp, *(bp - 1), repeat);
3859 printf_filtered ("Repeat count %d too large for buffer: ", repeat);
3860 puts_filtered (buf);
3861 puts_filtered ("\n");
3865 if (bp < buf + PBUFSIZ - 1)
3873 puts_filtered ("Remote packet too long: ");
3874 puts_filtered (buf);
3875 puts_filtered ("\n");
3882 /* Read a packet from the remote machine, with error checking, and
3883 store it in BUF. BUF is expected to be of size PBUFSIZ. If
3884 FOREVER, wait forever rather than timing out; this is used while
3885 the target is executing user code. */
3888 getpkt (buf, forever)
3897 strcpy (buf, "timeout");
3901 timeout = watchdog > 0 ? watchdog : -1;
3905 timeout = remote_timeout;
3909 for (tries = 1; tries <= MAX_TRIES; tries++)
3911 /* This can loop forever if the remote side sends us characters
3912 continuously, but if it pauses, we'll get a zero from readchar
3913 because of timeout. Then we'll count that as a retry. */
3915 /* Note that we will only wait forever prior to the start of a packet.
3916 After that, we expect characters to arrive at a brisk pace. They
3917 should show up within remote_timeout intervals. */
3921 c = readchar (timeout);
3923 if (c == SERIAL_TIMEOUT)
3925 if (forever) /* Watchdog went off? Kill the target. */
3928 target_mourn_inferior ();
3929 error ("Watchdog has expired. Target detached.\n");
3932 fputs_filtered ("Timed out.\n", gdb_stdlog);
3938 /* We've found the start of a packet, now collect the data. */
3940 val = read_frame (buf);
3946 fprintf_unfiltered (gdb_stdlog, "Packet received: ");
3947 fputstr_unfiltered (buf, 0, gdb_stdlog);
3948 fprintf_unfiltered (gdb_stdlog, "\n");
3950 SERIAL_WRITE (remote_desc, "+", 1);
3954 /* Try the whole thing again. */
3956 SERIAL_WRITE (remote_desc, "-", 1);
3959 /* We have tried hard enough, and just can't receive the packet. Give up. */
3961 printf_unfiltered ("Ignoring packet error, continuing...\n");
3962 SERIAL_WRITE (remote_desc, "+", 1);
3968 /* For some mysterious reason, wait_for_inferior calls kill instead of
3969 mourn after it gets TARGET_WAITKIND_SIGNALLED. Work around it. */
3973 target_mourn_inferior ();
3977 /* Use catch_errors so the user can quit from gdb even when we aren't on
3978 speaking terms with the remote system. */
3979 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
3981 /* Don't wait for it to die. I'm not really sure it matters whether
3982 we do or not. For the existing stubs, kill is a noop. */
3983 target_mourn_inferior ();
3986 /* Async version of remote_kill. */
3988 remote_async_kill ()
3990 /* Unregister the file descriptor from the event loop. */
3991 if (SERIAL_IS_ASYNC_P (remote_desc))
3992 SERIAL_ASYNC (remote_desc, NULL, 0);
3994 /* For some mysterious reason, wait_for_inferior calls kill instead of
3995 mourn after it gets TARGET_WAITKIND_SIGNALLED. Work around it. */
3999 target_mourn_inferior ();
4003 /* Use catch_errors so the user can quit from gdb even when we aren't on
4004 speaking terms with the remote system. */
4005 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
4007 /* Don't wait for it to die. I'm not really sure it matters whether
4008 we do or not. For the existing stubs, kill is a noop. */
4009 target_mourn_inferior ();
4015 remote_mourn_1 (&remote_ops);
4019 remote_async_mourn ()
4021 remote_mourn_1 (&remote_async_ops);
4025 extended_remote_mourn ()
4027 /* We do _not_ want to mourn the target like this; this will
4028 remove the extended remote target from the target stack,
4029 and the next time the user says "run" it'll fail.
4031 FIXME: What is the right thing to do here? */
4033 remote_mourn_1 (&extended_remote_ops);
4037 /* Worker function for remote_mourn. */
4039 remote_mourn_1 (target)
4040 struct target_ops *target;
4042 unpush_target (target);
4043 generic_mourn_inferior ();
4046 /* In the extended protocol we want to be able to do things like
4047 "run" and have them basically work as expected. So we need
4048 a special create_inferior function.
4050 FIXME: One day add support for changing the exec file
4051 we're debugging, arguments and an environment. */
4054 extended_remote_create_inferior (exec_file, args, env)
4059 /* Rip out the breakpoints; we'll reinsert them after restarting
4060 the remote server. */
4061 remove_breakpoints ();
4063 /* Now restart the remote server. */
4064 extended_remote_restart ();
4066 /* Now put the breakpoints back in. This way we're safe if the
4067 restart function works via a unix fork on the remote side. */
4068 insert_breakpoints ();
4070 /* Clean up from the last time we were running. */
4071 clear_proceed_status ();
4073 /* Let the remote process run. */
4074 proceed (-1, TARGET_SIGNAL_0, 0);
4077 /* Async version of extended_remote_create_inferior. */
4079 extended_remote_async_create_inferior (exec_file, args, env)
4084 /* Rip out the breakpoints; we'll reinsert them after restarting
4085 the remote server. */
4086 remove_breakpoints ();
4088 /* If running asynchronously, register the target file descriptor
4089 with the event loop. */
4090 if (event_loop_p && target_can_async_p ())
4091 target_async (inferior_event_handler, 0);
4093 /* Now restart the remote server. */
4094 extended_remote_restart ();
4096 /* Now put the breakpoints back in. This way we're safe if the
4097 restart function works via a unix fork on the remote side. */
4098 insert_breakpoints ();
4100 /* Clean up from the last time we were running. */
4101 clear_proceed_status ();
4103 /* Let the remote process run. */
4104 proceed (-1, TARGET_SIGNAL_0, 0);
4108 /* On some machines, e.g. 68k, we may use a different breakpoint instruction
4109 than other targets; in those use REMOTE_BREAKPOINT instead of just
4110 BREAKPOINT. Also, bi-endian targets may define LITTLE_REMOTE_BREAKPOINT
4111 and BIG_REMOTE_BREAKPOINT. If none of these are defined, we just call
4112 the standard routines that are in mem-break.c. */
4114 /* FIXME, these ought to be done in a more dynamic fashion. For instance,
4115 the choice of breakpoint instruction affects target program design and
4116 vice versa, and by making it user-tweakable, the special code here
4117 goes away and we need fewer special GDB configurations. */
4119 #if defined (LITTLE_REMOTE_BREAKPOINT) && defined (BIG_REMOTE_BREAKPOINT) && !defined(REMOTE_BREAKPOINT)
4120 #define REMOTE_BREAKPOINT
4123 #ifdef REMOTE_BREAKPOINT
4125 /* If the target isn't bi-endian, just pretend it is. */
4126 #if !defined (LITTLE_REMOTE_BREAKPOINT) && !defined (BIG_REMOTE_BREAKPOINT)
4127 #define LITTLE_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
4128 #define BIG_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
4131 static unsigned char big_break_insn[] = BIG_REMOTE_BREAKPOINT;
4132 static unsigned char little_break_insn[] = LITTLE_REMOTE_BREAKPOINT;
4134 #endif /* REMOTE_BREAKPOINT */
4136 /* Insert a breakpoint on targets that don't have any better breakpoint
4137 support. We read the contents of the target location and stash it,
4138 then overwrite it with a breakpoint instruction. ADDR is the target
4139 location in the target machine. CONTENTS_CACHE is a pointer to
4140 memory allocated for saving the target contents. It is guaranteed
4141 by the caller to be long enough to save sizeof BREAKPOINT bytes (this
4142 is accomplished via BREAKPOINT_MAX). */
4145 remote_insert_breakpoint (addr, contents_cache)
4147 char *contents_cache;
4149 #ifdef REMOTE_BREAKPOINT
4154 /* Try the "Z" packet if it is not already disabled.
4155 If it succeeds, then set the support to PACKET_ENABLE.
4156 If it fails, and the user has explicitly requested the Z support
4157 then report an error, otherwise, mark it disabled and go on. */
4159 if ((remote_protocol_Z.support == PACKET_ENABLE)
4160 || (remote_protocol_Z.support == PACKET_SUPPORT_UNKNOWN))
4162 char *buf = alloca (PBUFSIZ);
4165 addr = remote_address_masked (addr);
4169 p += hexnumstr (p, (ULONGEST) addr);
4170 BREAKPOINT_FROM_PC (&addr, &bp_size);
4171 sprintf (p, ",%d", bp_size);
4178 remote_protocol_Z.support = PACKET_ENABLE;
4179 return (buf[0] == 'E');
4182 /* The stub does not support the 'Z' request. If the user has
4183 explicitly requested the Z support, or if the stub previously
4184 said it supported the packet, this is an error,
4185 otherwise, mark it disabled. */
4187 else if (remote_protocol_Z.support == PACKET_ENABLE)
4189 error ("Protocol error: Z packet not recognized by stub");
4193 remote_protocol_Z.support = PACKET_DISABLE;
4197 #ifdef REMOTE_BREAKPOINT
4198 val = target_read_memory (addr, contents_cache, sizeof big_break_insn);
4202 if (TARGET_BYTE_ORDER == BIG_ENDIAN)
4203 val = target_write_memory (addr, (char *) big_break_insn,
4204 sizeof big_break_insn);
4206 val = target_write_memory (addr, (char *) little_break_insn,
4207 sizeof little_break_insn);
4212 return memory_insert_breakpoint (addr, contents_cache);
4213 #endif /* REMOTE_BREAKPOINT */
4217 remote_remove_breakpoint (addr, contents_cache)
4219 char *contents_cache;
4223 if ((remote_protocol_Z.support == PACKET_ENABLE)
4224 || (remote_protocol_Z.support == PACKET_SUPPORT_UNKNOWN))
4226 char *buf = alloca (PBUFSIZ);
4233 addr = remote_address_masked (addr);
4234 p += hexnumstr (p, (ULONGEST) addr);
4235 BREAKPOINT_FROM_PC (&addr, &bp_size);
4236 sprintf (p, ",%d", bp_size);
4241 return (buf[0] == 'E');
4244 #ifdef REMOTE_BREAKPOINT
4245 return target_write_memory (addr, contents_cache, sizeof big_break_insn);
4247 return memory_remove_breakpoint (addr, contents_cache);
4248 #endif /* REMOTE_BREAKPOINT */
4251 #ifdef TARGET_HAS_HARDWARE_WATCHPOINTS
4253 remote_insert_watchpoint (addr, len, type)
4258 char *buf = alloca (PBUFSIZ);
4261 if (remote_protocol_Z.support == PACKET_DISABLE)
4262 error ("Can't set hardware watchpoints without the 'Z' packet\n");
4264 sprintf (buf, "Z%x,", type + 2 );
4265 p = strchr (buf, '\0');
4266 addr = remote_address_masked (addr);
4267 p += hexnumstr (p, (ULONGEST) addr);
4268 sprintf (p, ",%x", len);
4273 if (buf[0] == '\0' || buf [0] == 'E')
4280 remote_remove_watchpoint (addr, len, type)
4285 char *buf = alloca (PBUFSIZ);
4288 sprintf (buf, "z%x,", type + 2 );
4289 p = strchr (buf, '\0');
4290 addr = remote_address_masked (addr);
4291 p += hexnumstr (p, (ULONGEST) addr);
4292 sprintf (p, ",%x", len);
4296 if (buf[0] == '\0' || buf [0] == 'E')
4303 remote_insert_hw_breakpoint (addr, len)
4307 char *buf = alloca (PBUFSIZ);
4310 if (remote_protocol_Z.support == PACKET_DISABLE)
4311 error ("Can't set hardware breakpoints without the 'Z' packet\n");
4317 addr = remote_address_masked (addr);
4318 p += hexnumstr (p, (ULONGEST) addr);
4324 if (buf[0] == '\0' || buf [0] == 'E')
4331 remote_remove_hw_breakpoint (addr, len)
4335 char *buf = alloca (PBUFSIZ);
4342 addr = remote_address_masked (addr);
4343 p += hexnumstr (p, (ULONGEST) addr);
4349 if (buf[0] == '\0' || buf [0] == 'E')
4356 /* Some targets are only capable of doing downloads, and afterwards
4357 they switch to the remote serial protocol. This function provides
4358 a clean way to get from the download target to the remote target.
4359 It's basically just a wrapper so that we don't have to expose any
4360 of the internal workings of remote.c.
4362 Prior to calling this routine, you should shutdown the current
4363 target code, else you will get the "A program is being debugged
4364 already..." message. Usually a call to pop_target() suffices. */
4367 push_remote_target (name, from_tty)
4371 printf_filtered ("Switching to remote protocol\n");
4372 remote_open (name, from_tty);
4375 /* Other targets want to use the entire remote serial module but with
4376 certain remote_ops overridden. */
4379 open_remote_target (name, from_tty, target, extended_p)
4382 struct target_ops *target;
4385 printf_filtered ("Selecting the %sremote protocol\n",
4386 (extended_p ? "extended-" : ""));
4387 remote_open_1 (name, from_tty, target, extended_p);
4390 /* Table used by the crc32 function to calcuate the checksum. */
4392 static unsigned long crc32_table[256] =
4395 static unsigned long
4396 crc32 (buf, len, crc)
4401 if (!crc32_table[1])
4403 /* Initialize the CRC table and the decoding table. */
4407 for (i = 0; i < 256; i++)
4409 for (c = i << 24, j = 8; j > 0; --j)
4410 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
4417 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
4423 /* compare-sections command
4425 With no arguments, compares each loadable section in the exec bfd
4426 with the same memory range on the target, and reports mismatches.
4427 Useful for verifying the image on the target against the exec file.
4428 Depends on the target understanding the new "qCRC:" request. */
4430 /* FIXME: cagney/1999-10-26: This command should be broken down into a
4431 target method (target verify memory) and generic version of the
4432 actual command. This will allow other high-level code (especially
4433 generic_load()) to make use of this target functionality. */
4436 compare_sections_command (args, from_tty)
4441 unsigned long host_crc, target_crc;
4442 extern bfd *exec_bfd;
4443 struct cleanup *old_chain;
4447 char *buf = alloca (PBUFSIZ);
4454 error ("command cannot be used without an exec file");
4455 if (!current_target.to_shortname ||
4456 strcmp (current_target.to_shortname, "remote") != 0)
4457 error ("command can only be used with remote target");
4459 for (s = exec_bfd->sections; s; s = s->next)
4461 if (!(s->flags & SEC_LOAD))
4462 continue; /* skip non-loadable section */
4464 size = bfd_get_section_size_before_reloc (s);
4466 continue; /* skip zero-length section */
4468 sectname = (char *) bfd_get_section_name (exec_bfd, s);
4469 if (args && strcmp (args, sectname) != 0)
4470 continue; /* not the section selected by user */
4472 matched = 1; /* do this section */
4474 /* FIXME: assumes lma can fit into long */
4475 sprintf (buf, "qCRC:%lx,%lx", (long) lma, (long) size);
4478 /* be clever; compute the host_crc before waiting for target reply */
4479 sectdata = xmalloc (size);
4480 old_chain = make_cleanup (free, sectdata);
4481 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
4482 host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
4486 error ("target memory fault, section %s, range 0x%08x -- 0x%08x",
4487 sectname, lma, lma + size);
4489 error ("remote target does not support this operation");
4491 for (target_crc = 0, tmp = &buf[1]; *tmp; tmp++)
4492 target_crc = target_crc * 16 + fromhex (*tmp);
4494 printf_filtered ("Section %s, range 0x%s -- 0x%s: ",
4495 sectname, paddr (lma), paddr (lma + size));
4496 if (host_crc == target_crc)
4497 printf_filtered ("matched.\n");
4500 printf_filtered ("MIS-MATCHED!\n");
4504 do_cleanups (old_chain);
4507 warning ("One or more sections of the remote executable does not match\n\
4508 the loaded file\n");
4509 if (args && !matched)
4510 printf_filtered ("No loaded section named '%s'.\n", args);
4514 remote_query (query_type, buf, outbuf, bufsiz)
4521 char *buf2 = alloca (PBUFSIZ);
4522 char *p2 = &buf2[0];
4525 error ("null pointer to remote bufer size specified");
4527 /* minimum outbuf size is PBUFSIZ - if bufsiz is not large enough let
4528 the caller know and return what the minimum size is */
4529 /* Note: a zero bufsiz can be used to query the minimum buffer size */
4530 if (*bufsiz < PBUFSIZ)
4536 /* except for querying the minimum buffer size, target must be open */
4538 error ("remote query is only available after target open");
4540 /* we only take uppercase letters as query types, at least for now */
4541 if ((query_type < 'A') || (query_type > 'Z'))
4542 error ("invalid remote query type");
4545 error ("null remote query specified");
4548 error ("remote query requires a buffer to receive data");
4555 /* we used one buffer char for the remote protocol q command and another
4556 for the query type. As the remote protocol encapsulation uses 4 chars
4557 plus one extra in case we are debugging (remote_debug),
4558 we have PBUFZIZ - 7 left to pack the query string */
4560 while (buf[i] && (i < (PBUFSIZ - 8)))
4562 /* bad caller may have sent forbidden characters */
4563 if ((!isprint (buf[i])) || (buf[i] == '$') || (buf[i] == '#'))
4564 error ("illegal characters in query string");
4572 error ("query larger than available buffer");
4584 remote_rcmd (char *command,
4585 struct gdb_file *outbuf)
4588 char *buf = alloca (PBUFSIZ);
4592 error ("remote rcmd is only available after target open");
4594 /* Send a NULL command across as an empty command */
4595 if (command == NULL)
4598 /* The query prefix */
4599 strcpy (buf, "qRcmd,");
4600 p = strchr (buf, '\0');
4602 if ((strlen (buf) + strlen (command) * 2 + 8/*misc*/) > PBUFSIZ)
4603 error ("\"monitor\" command ``%s'' is too long\n", command);
4605 /* Encode the actual command */
4606 for (i = 0; command[i]; i++)
4608 *p++ = tohex ((command[i] >> 4) & 0xf);
4609 *p++ = tohex (command[i] & 0xf);
4613 if (putpkt (buf) < 0)
4614 error ("Communication problem with target\n");
4616 /* get/display the response */
4619 /* XXX - see also tracepoint.c:remote_get_noisy_reply() */
4623 error ("Target does not support this command\n");
4624 if (buf[0] == 'O' && buf[1] != 'K')
4626 remote_console_output (buf + 1); /* 'O' message from stub */
4629 if (strcmp (buf, "OK") == 0)
4631 if (strlen (buf) == 3 && buf[0] == 'E'
4632 && isdigit (buf[1]) && isdigit (buf[2]))
4634 error ("Protocol error with Rcmd");
4636 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
4638 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
4639 fputc_unfiltered (c, outbuf);
4646 packet_command (args, from_tty)
4650 char *buf = alloca (PBUFSIZ);
4653 error ("command can only be used with remote target");
4656 error ("remote-packet command requires packet text as argument");
4658 puts_filtered ("sending: ");
4659 print_packet (args);
4660 puts_filtered ("\n");
4664 puts_filtered ("received: ");
4666 puts_filtered ("\n");
4670 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------------- */
4672 static void display_thread_info PARAMS ((struct gdb_ext_thread_info * info));
4674 static void threadset_test_cmd PARAMS ((char *cmd, int tty));
4676 static void threadalive_test PARAMS ((char *cmd, int tty));
4678 static void threadlist_test_cmd PARAMS ((char *cmd, int tty));
4680 int get_and_display_threadinfo PARAMS ((threadref * ref));
4682 static void threadinfo_test_cmd PARAMS ((char *cmd, int tty));
4684 static int thread_display_step PARAMS ((threadref * ref, void *context));
4686 static void threadlist_update_test_cmd PARAMS ((char *cmd, int tty));
4688 static void init_remote_threadtests PARAMS ((void));
4690 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid */
4693 threadset_test_cmd (cmd, tty)
4697 int sample_thread = SAMPLE_THREAD;
4699 printf_filtered ("Remote threadset test\n");
4700 set_thread (sample_thread, 1);
4705 threadalive_test (cmd, tty)
4709 int sample_thread = SAMPLE_THREAD;
4711 if (remote_thread_alive (sample_thread))
4712 printf_filtered ("PASS: Thread alive test\n");
4714 printf_filtered ("FAIL: Thread alive test\n");
4717 void output_threadid PARAMS ((char *title, threadref * ref));
4720 output_threadid (title, ref)
4726 pack_threadid (&hexid[0], ref); /* Convert threead id into hex */
4728 printf_filtered ("%s %s\n", title, (&hexid[0]));
4732 threadlist_test_cmd (cmd, tty)
4737 threadref nextthread;
4738 int done, result_count;
4739 threadref threadlist[3];
4741 printf_filtered ("Remote Threadlist test\n");
4742 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
4743 &result_count, &threadlist[0]))
4744 printf_filtered ("FAIL: threadlist test\n");
4747 threadref *scan = threadlist;
4748 threadref *limit = scan + result_count;
4750 while (scan < limit)
4751 output_threadid (" thread ", scan++);
4756 display_thread_info (info)
4757 struct gdb_ext_thread_info *info;
4759 output_threadid ("Threadid: ", &info->threadid);
4760 printf_filtered ("Name: %s\n ", info->shortname);
4761 printf_filtered ("State: %s\n", info->display);
4762 printf_filtered ("other: %s\n\n", info->more_display);
4766 get_and_display_threadinfo (ref)
4771 struct gdb_ext_thread_info threadinfo;
4773 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
4774 | TAG_MOREDISPLAY | TAG_DISPLAY;
4775 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
4776 display_thread_info (&threadinfo);
4781 threadinfo_test_cmd (cmd, tty)
4785 int athread = SAMPLE_THREAD;
4789 int_to_threadref (&thread, athread);
4790 printf_filtered ("Remote Threadinfo test\n");
4791 if (!get_and_display_threadinfo (&thread))
4792 printf_filtered ("FAIL cannot get thread info\n");
4796 thread_display_step (ref, context)
4800 /* output_threadid(" threadstep ",ref); *//* simple test */
4801 return get_and_display_threadinfo (ref);
4805 threadlist_update_test_cmd (cmd, tty)
4809 printf_filtered ("Remote Threadlist update test\n");
4810 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
4814 init_remote_threadtests (void)
4816 add_com ("tlist", class_obscure, threadlist_test_cmd,
4817 "Fetch and print the remote list of thread identifiers, one pkt only");
4818 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
4819 "Fetch and display info about one thread");
4820 add_com ("tset", class_obscure, threadset_test_cmd,
4821 "Test setting to a different thread");
4822 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
4823 "Iterate through updating all remote thread info");
4824 add_com ("talive", class_obscure, threadalive_test,
4825 " Remote thread alive test ");
4833 remote_ops.to_shortname = "remote";
4834 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
4836 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
4837 Specify the serial device it is connected to (e.g. /dev/ttya).";
4838 remote_ops.to_open = remote_open;
4839 remote_ops.to_close = remote_close;
4840 remote_ops.to_detach = remote_detach;
4841 remote_ops.to_resume = remote_resume;
4842 remote_ops.to_wait = remote_wait;
4843 remote_ops.to_fetch_registers = remote_fetch_registers;
4844 remote_ops.to_store_registers = remote_store_registers;
4845 remote_ops.to_prepare_to_store = remote_prepare_to_store;
4846 remote_ops.to_xfer_memory = remote_xfer_memory;
4847 remote_ops.to_files_info = remote_files_info;
4848 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
4849 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
4850 remote_ops.to_kill = remote_kill;
4851 remote_ops.to_load = generic_load;
4852 remote_ops.to_mourn_inferior = remote_mourn;
4853 remote_ops.to_thread_alive = remote_thread_alive;
4854 remote_ops.to_find_new_threads = remote_threads_info;
4855 remote_ops.to_stop = remote_stop;
4856 remote_ops.to_query = remote_query;
4857 remote_ops.to_rcmd = remote_rcmd;
4858 remote_ops.to_stratum = process_stratum;
4859 remote_ops.to_has_all_memory = 1;
4860 remote_ops.to_has_memory = 1;
4861 remote_ops.to_has_stack = 1;
4862 remote_ops.to_has_registers = 1;
4863 remote_ops.to_has_execution = 1;
4864 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
4865 remote_ops.to_magic = OPS_MAGIC;
4868 /* Set up the extended remote vector by making a copy of the standard
4869 remote vector and adding to it. */
4872 init_extended_remote_ops ()
4874 extended_remote_ops = remote_ops;
4876 extended_remote_ops.to_shortname = "extended-remote";
4877 extended_remote_ops.to_longname =
4878 "Extended remote serial target in gdb-specific protocol";
4879 extended_remote_ops.to_doc =
4880 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
4881 Specify the serial device it is connected to (e.g. /dev/ttya).",
4882 extended_remote_ops.to_open = extended_remote_open;
4883 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
4884 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
4888 * Command: info remote-process
4890 * This implements Cisco's version of the "info proc" command.
4892 * This query allows the target stub to return an arbitrary string
4893 * (or strings) giving arbitrary information about the target process.
4894 * This is optional; the target stub isn't required to implement it.
4896 * Syntax: qfProcessInfo request first string
4897 * qsProcessInfo request subsequent string
4898 * reply: 'O'<hex-encoded-string>
4899 * 'l' last reply (empty)
4903 remote_info_process (args, from_tty)
4907 char *buf = alloca (PBUFSIZ);
4909 if (remote_desc == 0)
4910 error ("Command can only be used when connected to the remote target.");
4912 putpkt ("qfProcessInfo");
4915 return; /* Silently: target does not support this feature. */
4918 error ("info proc: target error.");
4920 while (buf[0] == 'O') /* Capitol-O packet */
4922 remote_console_output (&buf[1]);
4923 putpkt ("qsProcessInfo");
4933 remote_cisco_open (name, from_tty)
4939 "To open a remote debug connection, you need to specify what \n\
4940 device is attached to the remote system (e.g. host:port).");
4942 /* See FIXME above */
4943 wait_forever_enabled_p = 1;
4945 target_preopen (from_tty);
4947 unpush_target (&remote_cisco_ops);
4949 remote_dcache = dcache_init (remote_read_bytes, remote_write_bytes);
4951 remote_desc = SERIAL_OPEN (name);
4953 perror_with_name (name);
4956 * If a baud rate was specified on the gdb command line it will
4957 * be greater than the initial value of -1. If it is, use it otherwise
4961 baud_rate = (baud_rate > 0) ? baud_rate : 9600;
4962 if (SERIAL_SETBAUDRATE (remote_desc, baud_rate))
4964 SERIAL_CLOSE (remote_desc);
4965 perror_with_name (name);
4968 SERIAL_RAW (remote_desc);
4970 /* If there is something sitting in the buffer we might take it as a
4971 response to a command, which would be bad. */
4972 SERIAL_FLUSH_INPUT (remote_desc);
4976 puts_filtered ("Remote debugging using ");
4977 puts_filtered (name);
4978 puts_filtered ("\n");
4981 remote_cisco_mode = 1;
4983 push_target (&remote_cisco_ops); /* Switch to using cisco target now */
4985 init_packet_config (&remote_protocol_P);
4986 init_packet_config (&remote_protocol_Z);
4988 general_thread = -2;
4989 continue_thread = -2;
4991 /* Force remote_write_bytes to check whether target supports
4992 binary downloading. */
4993 init_packet_config (&remote_protocol_binary_download);
4995 /* Without this, some commands which require an active target (such
4996 as kill) won't work. This variable serves (at least) double duty
4997 as both the pid of the target process (if it has such), and as a
4998 flag indicating that a target is active. These functions should
4999 be split out into seperate variables, especially since GDB will
5000 someday have a notion of debugging several processes. */
5001 inferior_pid = MAGIC_NULL_PID;
5003 /* Start the remote connection; if error (0), discard this target. */
5005 if (!catch_errors (remote_start_remote_dummy, (char *) 0,
5006 "Couldn't establish connection to remote target\n",
5015 remote_cisco_close (quitting)
5018 remote_cisco_mode = 0;
5019 remote_close (quitting);
5026 remote_mourn_1 (&remote_cisco_ops);
5038 /* shared between readsocket() and readtty() */
5039 static char *tty_input;
5041 static int escape_count;
5042 static int echo_check;
5043 extern int quit_flag;
5050 /* Loop until the socket doesn't have any more data */
5052 while ((data = readchar (0)) >= 0)
5054 /* Check for the escape sequence */
5057 /* If this is the fourth escape, get out */
5058 if (++escape_count == 4)
5063 { /* This is a '|', but not the fourth in a row.
5064 Continue without echoing it. If it isn't actually
5065 one of four in a row, it'll be echoed later. */
5072 /* Ensure any pending '|'s are flushed. */
5074 for (; escape_count > 0; escape_count--)
5078 if (data == '\r') /* If this is a return character, */
5079 continue; /* - just supress it. */
5081 if (echo_check != -1) /* Check for echo of user input. */
5083 if (tty_input[echo_check] == data)
5085 echo_check++; /* Character matched user input: */
5086 continue; /* Continue without echoing it. */
5088 else if ((data == '\n') && (tty_input[echo_check] == '\r'))
5089 { /* End of the line (and of echo checking). */
5090 echo_check = -1; /* No more echo supression */
5091 continue; /* Continue without echoing. */
5094 { /* Failed check for echo of user input.
5095 We now have some suppressed output to flush! */
5098 for (j = 0; j < echo_check; j++)
5099 putchar (tty_input[j]);
5103 putchar (data); /* Default case: output the char. */
5106 if (data == SERIAL_TIMEOUT) /* Timeout returned from readchar. */
5107 return READ_MORE; /* Try to read some more */
5109 return FATAL_ERROR; /* Trouble, bail out */
5117 /* First, read a buffer full from the terminal */
5118 tty_bytecount = read (fileno (stdin), tty_input, sizeof (tty_input) - 1);
5119 if (tty_bytecount == -1)
5121 perror ("readtty: read failed");
5125 /* Remove a quoted newline. */
5126 if (tty_input[tty_bytecount - 1] == '\n' &&
5127 tty_input[tty_bytecount - 2] == '\\') /* line ending in backslash */
5129 tty_input[--tty_bytecount] = 0; /* remove newline */
5130 tty_input[--tty_bytecount] = 0; /* remove backslash */
5133 /* Turn trailing newlines into returns */
5134 if (tty_input[tty_bytecount - 1] == '\n')
5135 tty_input[tty_bytecount - 1] = '\r';
5137 /* If the line consists of a ~, enter debugging mode. */
5138 if ((tty_input[0] == '~') && (tty_bytecount == 2))
5141 /* Make this a zero terminated string and write it out */
5142 tty_input[tty_bytecount] = 0;
5143 if (SERIAL_WRITE (remote_desc, tty_input, tty_bytecount))
5145 perror_with_name ("readtty: write failed");
5155 fd_set input; /* file descriptors for select */
5156 int tablesize; /* max number of FDs for select */
5160 extern int escape_count; /* global shared by readsocket */
5161 extern int echo_check; /* ditto */
5166 tablesize = 8 * sizeof (input);
5170 /* Check for anything from our socket - doesn't block. Note that
5171 this must be done *before* the select as there may be
5172 buffered I/O waiting to be processed. */
5174 if ((status = readsocket ()) == FATAL_ERROR)
5176 error ("Debugging terminated by communications error");
5178 else if (status != READ_MORE)
5183 fflush (stdout); /* Flush output before blocking */
5185 /* Now block on more socket input or TTY input */
5188 FD_SET (fileno (stdin), &input);
5189 FD_SET (DEPRECATED_SERIAL_FD (remote_desc), &input);
5191 status = select (tablesize, &input, 0, 0, 0);
5192 if ((status == -1) && (errno != EINTR))
5194 error ("Communications error on select %d", errno);
5197 /* Handle Control-C typed */
5201 if ((++quit_count) == 2)
5203 if (query ("Interrupt GDB? "))
5205 printf_filtered ("Interrupted by user.\n");
5206 return_to_top_level (RETURN_QUIT);
5213 SERIAL_SEND_BREAK (remote_desc);
5215 SERIAL_WRITE (remote_desc, "\003", 1);
5220 /* Handle console input */
5222 if (FD_ISSET (fileno (stdin), &input))
5226 status = readtty ();
5227 if (status == READ_MORE)
5230 return status; /* telnet session ended */
5236 remote_cisco_wait (pid, status)
5238 struct target_waitstatus *status;
5240 if (minitelnet () != ENTER_DEBUG)
5242 error ("Debugging session terminated by protocol error");
5245 return remote_wait (pid, status);
5249 init_remote_cisco_ops ()
5251 remote_cisco_ops.to_shortname = "cisco";
5252 remote_cisco_ops.to_longname = "Remote serial target in cisco-specific protocol";
5253 remote_cisco_ops.to_doc =
5254 "Use a remote machine via TCP, using a cisco-specific protocol.\n\
5255 Specify the serial device it is connected to (e.g. host:2020).";
5256 remote_cisco_ops.to_open = remote_cisco_open;
5257 remote_cisco_ops.to_close = remote_cisco_close;
5258 remote_cisco_ops.to_detach = remote_detach;
5259 remote_cisco_ops.to_resume = remote_resume;
5260 remote_cisco_ops.to_wait = remote_cisco_wait;
5261 remote_cisco_ops.to_fetch_registers = remote_fetch_registers;
5262 remote_cisco_ops.to_store_registers = remote_store_registers;
5263 remote_cisco_ops.to_prepare_to_store = remote_prepare_to_store;
5264 remote_cisco_ops.to_xfer_memory = remote_xfer_memory;
5265 remote_cisco_ops.to_files_info = remote_files_info;
5266 remote_cisco_ops.to_insert_breakpoint = remote_insert_breakpoint;
5267 remote_cisco_ops.to_remove_breakpoint = remote_remove_breakpoint;
5268 remote_cisco_ops.to_kill = remote_kill;
5269 remote_cisco_ops.to_load = generic_load;
5270 remote_cisco_ops.to_mourn_inferior = remote_cisco_mourn;
5271 remote_cisco_ops.to_thread_alive = remote_thread_alive;
5272 remote_cisco_ops.to_find_new_threads = remote_threads_info;
5273 remote_cisco_ops.to_stratum = process_stratum;
5274 remote_cisco_ops.to_has_all_memory = 1;
5275 remote_cisco_ops.to_has_memory = 1;
5276 remote_cisco_ops.to_has_stack = 1;
5277 remote_cisco_ops.to_has_registers = 1;
5278 remote_cisco_ops.to_has_execution = 1;
5279 remote_cisco_ops.to_magic = OPS_MAGIC;
5283 remote_can_async_p (void)
5285 /* We're async whenever the serial device is. */
5286 return SERIAL_CAN_ASYNC_P (remote_desc);
5290 remote_is_async_p (void)
5292 /* We're async whenever the serial device is. */
5293 return SERIAL_IS_ASYNC_P (remote_desc);
5296 /* Pass the SERIAL event on and up to the client. One day this code
5297 will be able to delay notifying the client of an event until the
5298 point where an entire packet has been received. */
5300 static void (*async_client_callback) (enum inferior_event_type event_type, void *context);
5301 static void *async_client_context;
5302 static serial_event_ftype remote_async_serial_handler;
5305 remote_async_serial_handler (serial_t scb, void *context)
5307 /* Don't propogate error information up to the client. Instead let
5308 the client find out about the error by querying the target. */
5309 async_client_callback (INF_REG_EVENT, async_client_context);
5313 remote_async (void (*callback) (enum inferior_event_type event_type, void *context), void *context)
5315 if (callback != NULL)
5317 SERIAL_ASYNC (remote_desc, remote_async_serial_handler, NULL);
5318 async_client_callback = callback;
5319 async_client_context = context;
5322 SERIAL_ASYNC (remote_desc, NULL, NULL);
5325 /* Target async and target extended-async.
5327 This are temporary targets, until it is all tested. Eventually
5328 async support will be incorporated int the usual 'remote'
5332 init_remote_async_ops ()
5334 remote_async_ops.to_shortname = "async";
5335 remote_async_ops.to_longname = "Remote serial target in async version of the gdb-specific protocol";
5336 remote_async_ops.to_doc =
5337 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
5338 Specify the serial device it is connected to (e.g. /dev/ttya).";
5339 remote_async_ops.to_open = remote_async_open;
5340 remote_async_ops.to_close = remote_close;
5341 remote_async_ops.to_detach = remote_async_detach;
5342 remote_async_ops.to_resume = remote_async_resume;
5343 remote_async_ops.to_wait = remote_async_wait;
5344 remote_async_ops.to_fetch_registers = remote_fetch_registers;
5345 remote_async_ops.to_store_registers = remote_store_registers;
5346 remote_async_ops.to_prepare_to_store = remote_prepare_to_store;
5347 remote_async_ops.to_xfer_memory = remote_xfer_memory;
5348 remote_async_ops.to_files_info = remote_files_info;
5349 remote_async_ops.to_insert_breakpoint = remote_insert_breakpoint;
5350 remote_async_ops.to_remove_breakpoint = remote_remove_breakpoint;
5351 remote_async_ops.to_terminal_inferior = remote_async_terminal_inferior;
5352 remote_async_ops.to_terminal_ours = remote_async_terminal_ours;
5353 remote_async_ops.to_kill = remote_async_kill;
5354 remote_async_ops.to_load = generic_load;
5355 remote_async_ops.to_mourn_inferior = remote_async_mourn;
5356 remote_async_ops.to_thread_alive = remote_thread_alive;
5357 remote_async_ops.to_find_new_threads = remote_threads_info;
5358 remote_async_ops.to_stop = remote_stop;
5359 remote_async_ops.to_query = remote_query;
5360 remote_async_ops.to_rcmd = remote_rcmd;
5361 remote_async_ops.to_stratum = process_stratum;
5362 remote_async_ops.to_has_all_memory = 1;
5363 remote_async_ops.to_has_memory = 1;
5364 remote_async_ops.to_has_stack = 1;
5365 remote_async_ops.to_has_registers = 1;
5366 remote_async_ops.to_has_execution = 1;
5367 remote_async_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
5368 remote_async_ops.to_can_async_p = remote_can_async_p;
5369 remote_async_ops.to_is_async_p = remote_is_async_p;
5370 remote_async_ops.to_async = remote_async;
5371 remote_async_ops.to_magic = OPS_MAGIC;
5374 /* Set up the async extended remote vector by making a copy of the standard
5375 remote vector and adding to it. */
5378 init_extended_async_remote_ops ()
5380 extended_async_remote_ops = remote_async_ops;
5382 extended_async_remote_ops.to_shortname = "extended-async";
5383 extended_async_remote_ops.to_longname =
5384 "Extended remote serial target in async gdb-specific protocol";
5385 extended_async_remote_ops.to_doc =
5386 "Use a remote computer via a serial line, using an async gdb-specific protocol.\n\
5387 Specify the serial device it is connected to (e.g. /dev/ttya).",
5388 extended_async_remote_ops.to_open = extended_remote_async_open;
5389 extended_async_remote_ops.to_create_inferior = extended_remote_async_create_inferior;
5390 extended_async_remote_ops.to_mourn_inferior = extended_remote_mourn;
5394 set_remote_cmd (args, from_tty)
5403 build_remote_gdbarch_data ()
5405 build_remote_packet_sizes ();
5408 tty_input = xmalloc (PBUFSIZ);
5409 remote_address_size = TARGET_PTR_BIT;
5413 _initialize_remote ()
5415 static struct cmd_list_element *remote_set_cmdlist;
5416 static struct cmd_list_element *remote_show_cmdlist;
5417 struct cmd_list_element *tmpcmd;
5419 /* architecture specific data */
5420 build_remote_gdbarch_data ();
5421 register_gdbarch_swap (&tty_input, sizeof (&tty_input), NULL);
5422 register_remote_packet_sizes ();
5423 register_gdbarch_swap (&remote_address_size,
5424 sizeof (&remote_address_size), NULL);
5425 register_gdbarch_swap (NULL, 0, build_remote_gdbarch_data);
5428 add_target (&remote_ops);
5430 init_extended_remote_ops ();
5431 add_target (&extended_remote_ops);
5433 init_remote_async_ops ();
5434 add_target (&remote_async_ops);
5436 init_extended_async_remote_ops ();
5437 add_target (&extended_async_remote_ops);
5439 init_remote_cisco_ops ();
5440 add_target (&remote_cisco_ops);
5443 init_remote_threadtests ();
5446 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, "\
5447 Remote protocol specific variables\n\
5448 Configure various remote-protocol specific variables such as\n\
5449 the packets being used",
5450 &remote_set_cmdlist, "set remote ",
5451 0/*allow-unknown*/, &setlist);
5452 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, "\
5453 Remote protocol specific variables\n\
5454 Configure various remote-protocol specific variables such as\n\
5455 the packets being used",
5456 &remote_show_cmdlist, "show remote ",
5457 0/*allow-unknown*/, &showlist);
5459 add_cmd ("compare-sections", class_obscure, compare_sections_command,
5460 "Compare section data on target to the exec file.\n\
5461 Argument is a single section name (default: all loaded sections).",
5464 add_cmd ("packet", class_maintenance, packet_command,
5465 "Send an arbitrary packet to a remote target.\n\
5466 maintenance packet TEXT\n\
5467 If GDB is talking to an inferior via the GDB serial protocol, then\n\
5468 this command sends the string TEXT to the inferior, and displays the\n\
5469 response packet. GDB supplies the initial `$' character, and the\n\
5470 terminating `#' character and checksum.",
5474 (add_set_cmd ("remotetimeout", no_class,
5475 var_integer, (char *) &remote_timeout,
5476 "Set timeout value for remote read.\n",
5481 (add_set_cmd ("remotebreak", no_class,
5482 var_boolean, (char *) &remote_break,
5483 "Set whether to send break if interrupted.\n",
5487 /* Install commands for configuring memory read/write packets. */
5489 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size,
5490 "Set the maximum number of bytes per memory write packet (deprecated).\n",
5492 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size,
5493 "Show the maximum number of bytes per memory write packet (deprecated).\n",
5495 add_cmd ("memory-write-packet-size", no_class,
5496 set_memory_write_packet_size,
5497 "Set the maximum number of bytes per memory-write packet.\n"
5498 "Specify the number of bytes in a packet or 0 (zero) for the\n"
5499 "default packet size. The actual limit is further reduced\n"
5500 "dependent on the target. Specify ``fixed'' to disable the\n"
5501 "further restriction and ``limit'' to enable that restriction\n",
5502 &remote_set_cmdlist);
5503 add_cmd ("memory-read-packet-size", no_class,
5504 set_memory_read_packet_size,
5505 "Set the maximum number of bytes per memory-read packet.\n"
5506 "Specify the number of bytes in a packet or 0 (zero) for the\n"
5507 "default packet size. The actual limit is further reduced\n"
5508 "dependent on the target. Specify ``fixed'' to disable the\n"
5509 "further restriction and ``limit'' to enable that restriction\n",
5510 &remote_set_cmdlist);
5511 add_cmd ("memory-write-packet-size", no_class,
5512 show_memory_write_packet_size,
5513 "Show the maximum number of bytes per memory-write packet.\n",
5514 &remote_show_cmdlist);
5515 add_cmd ("memory-read-packet-size", no_class,
5516 show_memory_read_packet_size,
5517 "Show the maximum number of bytes per memory-read packet.\n",
5518 &remote_show_cmdlist);
5521 (add_set_cmd ("remoteaddresssize", class_obscure,
5522 var_integer, (char *) &remote_address_size,
5523 "Set the maximum size of the address (in bits) \
5524 in a memory packet.\n",
5528 add_packet_config_cmd (&remote_protocol_binary_download,
5529 "X", "binary-download",
5530 set_remote_protocol_binary_download_cmd,
5531 show_remote_protocol_binary_download_cmd,
5532 &remote_set_cmdlist, &remote_show_cmdlist);
5534 /* XXXX - should ``set remotebinarydownload'' be retained for
5537 (add_set_cmd ("remotebinarydownload", no_class,
5538 var_boolean, (char *) &remote_binary_download,
5539 "Set binary downloads.\n", &setlist),
5543 add_info ("remote-process", remote_info_process,
5544 "Query the remote system for process info.");
5546 add_packet_config_cmd (&remote_protocol_P, "P", "set-register",
5547 set_remote_protocol_P_packet_cmd,
5548 show_remote_protocol_P_packet_cmd,
5549 &remote_set_cmdlist, &remote_show_cmdlist);
5551 add_packet_config_cmd (&remote_protocol_Z, "Z", "breakpoint",
5552 set_remote_protocol_Z_packet_cmd,
5553 show_remote_protocol_Z_packet_cmd,
5554 &remote_set_cmdlist, &remote_show_cmdlist);