1 /* Remote target communications for serial-line targets in custom GDB protocol
2 Copyright 1988, 91, 92, 93, 94, 95, 96, 97, 1998
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, Boston, MA 02111-1307, USA. */
21 /* Remote communication protocol.
23 A debug packet whose contents are <data>
24 is encapsulated for transmission in the form:
26 $ <data> # CSUM1 CSUM2
28 <data> must be ASCII alphanumeric and cannot include characters
29 '$' or '#'. If <data> starts with two characters followed by
30 ':', then the existing stubs interpret this as a sequence number.
32 CSUM1 and CSUM2 are ascii hex representation of an 8-bit
33 checksum of <data>, the most significant nibble is sent first.
34 the hex digits 0-9,a-f are used.
36 Receiver responds with:
38 + - if CSUM is correct and ready for next packet
39 - - if CSUM is incorrect
42 Most values are encoded in ascii hex digits. Signal numbers are according
43 to the numbering in target.h.
47 set thread Hct... Set thread for subsequent operations.
48 c = 'c' for thread used in step and
49 continue; t... can be -1 for all
51 c = 'g' for thread used in other
52 operations. If zero, pick a thread,
58 reply XX....X Each byte of register data
59 is described by two hex digits.
60 Registers are in the internal order
61 for GDB, and the bytes in a register
62 are in the same order the machine uses.
65 write regs GXX..XX Each byte of register data
66 is described by two hex digits.
70 write reg Pn...=r... Write register n... with value r...,
71 which contains two hex digits for each
72 byte in the register (target byte
76 (not supported by all stubs).
78 read mem mAA..AA,LLLL AA..AA is address, LLLL is length.
79 reply XX..XX XX..XX is mem contents
80 Can be fewer bytes than requested
81 if able to read only part of the data.
84 write mem MAA..AA,LLLL:XX..XX
86 LLLL is number of bytes,
89 ENN for an error (this includes the case
90 where only part of the data was
93 write mem XAA..AA,LLLL:XX..XX
94 (binary) AA..AA is address,
95 LLLL is number of bytes,
100 continue cAA..AA AA..AA is address to resume
101 If AA..AA is omitted,
102 resume at same address.
104 step sAA..AA AA..AA is address to resume
105 If AA..AA is omitted,
106 resume at same address.
108 continue with Csig;AA..AA Continue with signal sig (hex signal
109 signal number). If ;AA..AA is omitted,
110 resume at same address.
112 step with Ssig;AA..AA Like 'C' but step not continue.
115 last signal ? Reply the current reason for stopping.
116 This is the same reply as is generated
117 for step or cont : SAA where AA is the
122 There is no immediate reply to step or cont.
123 The reply comes when the machine stops.
124 It is SAA AA is the signal number.
126 or... TAAn...:r...;n...:r...;n...:r...;
128 n... = register number (hex)
129 r... = register contents
131 r... = thread process ID. This is
133 n... = other string not starting
134 with valid hex digit.
135 gdb should ignore this n,r pair
136 and go on to the next. This way
137 we can extend the protocol.
138 or... WAA The process exited, and AA is
139 the exit status. This is only
140 applicable for certains sorts of
142 or... XAA The process terminated with signal
144 or... OXX..XX XX..XX is hex encoding of ASCII data. This
145 can happen at any time while the
146 program is running and the debugger
147 should continue to wait for
150 thread alive TXX Find out if the thread XX is alive.
151 reply OK thread is still alive
154 remote restart RXX Restart the remote server
156 extended ops ! Use the extended remote protocol.
157 Sticky -- only needs to be set once.
161 toggle debug d toggle debug flag (see 386 & 68k stubs)
162 reset r reset -- see sparc stub.
163 reserved <other> On other requests, the stub should
164 ignore the request and send an empty
165 response ($#<checksum>). This way
166 we can extend the protocol and GDB
167 can tell whether the stub it is
168 talking to uses the old or the new.
169 search tAA:PP,MM Search backwards starting at address
170 AA for a match with pattern PP and
171 mask MM. PP and MM are 4 bytes.
172 Not supported by all stubs.
174 general query qXXXX Request info about XXXX.
175 general set QXXXX=yyyy Set value of XXXX to yyyy.
176 query sect offs qOffsets Get section offsets. Reply is
177 Text=xxx;Data=yyy;Bss=zzz
179 Responses can be run-length encoded to save space. A '*' means that
180 the next character is an ASCII encoding giving a repeat count which
181 stands for that many repititions of the character preceding the '*'.
182 The encoding is n+29, yielding a printable character where n >=3
183 (which is where rle starts to win). Don't use an n > 126.
186 "0* " means the same as "0000". */
189 #include "gdb_string.h"
193 #include "inferior.h"
198 /*#include "terminal.h"*/
200 #include "objfiles.h"
201 #include "gdb-stabs.h"
202 #include "gdbthread.h"
207 #include <sys/types.h>
213 /* Prototypes for local functions */
215 static int remote_write_bytes PARAMS ((CORE_ADDR memaddr,
216 char *myaddr, int len));
218 static int remote_read_bytes PARAMS ((CORE_ADDR memaddr,
219 char *myaddr, int len));
221 static void remote_files_info PARAMS ((struct target_ops *ignore));
223 static int remote_xfer_memory PARAMS ((CORE_ADDR memaddr, char * myaddr,
224 int len, int should_write,
225 struct target_ops * target));
227 static void remote_prepare_to_store PARAMS ((void));
229 static void remote_fetch_registers PARAMS ((int regno));
231 static void remote_resume PARAMS ((int pid, int step,
232 enum target_signal siggnal));
234 static int remote_start_remote PARAMS ((PTR));
236 static void remote_open PARAMS ((char *name, int from_tty));
238 static void extended_remote_open PARAMS ((char *name, int from_tty));
240 static void remote_open_1 PARAMS ((char *, int, struct target_ops *,
243 static void remote_close PARAMS ((int quitting));
245 static void remote_store_registers PARAMS ((int regno));
247 static void remote_mourn PARAMS ((void));
249 static void extended_remote_restart PARAMS ((void));
251 static void extended_remote_mourn PARAMS ((void));
253 static void extended_remote_create_inferior PARAMS ((char *, char *, char **));
255 static void remote_mourn_1 PARAMS ((struct target_ops *));
257 static void remote_send PARAMS ((char *buf));
259 static int readchar PARAMS ((int timeout));
261 static int remote_wait PARAMS ((int pid, struct target_waitstatus * status));
263 static void remote_kill PARAMS ((void));
265 static int tohex PARAMS ((int nib));
267 static void remote_detach PARAMS ((char *args, int from_tty));
269 static void remote_interrupt PARAMS ((int signo));
271 static void interrupt_query PARAMS ((void));
273 static void set_thread PARAMS ((int, int));
275 static int remote_thread_alive PARAMS ((int));
277 static void get_offsets PARAMS ((void));
279 static int read_frame PARAMS ((char *));
281 static int remote_insert_breakpoint PARAMS ((CORE_ADDR, char *));
283 static int remote_remove_breakpoint PARAMS ((CORE_ADDR, char *));
285 static int hexnumlen PARAMS ((ULONGEST num));
287 static void init_remote_ops PARAMS ((void));
289 static void init_extended_remote_ops PARAMS ((void));
291 static void remote_stop PARAMS ((void));
293 static int ishex PARAMS ((int ch, int *val));
295 static int stubhex PARAMS ((int ch));
297 static int remote_query PARAMS ((int/*char*/, char *, char *, int *));
299 static int hexnumstr PARAMS ((char *, ULONGEST));
301 static CORE_ADDR remote_address_masked PARAMS ((CORE_ADDR));
303 static void print_packet PARAMS ((char *));
305 static unsigned long crc32 PARAMS ((unsigned char *, int, unsigned int));
307 static void compare_sections_command PARAMS ((char *, int));
309 static void packet_command PARAMS ((char *, int));
311 static int stub_unpack_int PARAMS ((char *buff, int fieldlength));
313 char *unpack_varlen_hex PARAMS ((char *buff, int *result));
315 static char *unpack_nibble PARAMS ((char *buf, int *val));
317 static char *pack_nibble PARAMS ((char *buf, int nibble));
319 static char *pack_hex_byte PARAMS ((char *pkt, int/*unsigned char*/ byte));
321 static char *unpack_byte PARAMS ((char *buf, int *value));
323 static char *pack_int PARAMS ((char *buf, int value));
325 static char *unpack_int PARAMS ((char *buf, int *value));
327 static char *unpack_string PARAMS ((char *src, char *dest, int length));
329 static char *pack_threadid PARAMS ((char *pkt, threadref *id));
331 static char *unpack_threadid PARAMS ((char *inbuf, threadref *id));
333 void int_to_threadref PARAMS ((threadref *id, int value));
335 static int threadref_to_int PARAMS ((threadref *ref));
337 static void copy_threadref PARAMS ((threadref *dest, threadref *src));
339 static int threadmatch PARAMS ((threadref *dest, threadref *src));
341 static char *pack_threadinfo_request PARAMS ((char *pkt, int mode,
344 static int remote_unpack_thread_info_response PARAMS ((char *pkt,
345 threadref *expectedref,
346 struct gdb_ext_thread_info *info));
349 static int remote_get_threadinfo PARAMS ((threadref *threadid,
350 int fieldset, /*TAG mask */
351 struct gdb_ext_thread_info *info));
353 static int adapt_remote_get_threadinfo PARAMS ((gdb_threadref *ref,
355 struct gdb_ext_thread_info *info));
357 static char *pack_threadlist_request PARAMS ((char *pkt, int startflag,
359 threadref *nextthread));
361 static int parse_threadlist_response PARAMS ((char *pkt,
363 threadref *original_echo,
364 threadref *resultlist,
367 static int remote_get_threadlist PARAMS ((int startflag,
368 threadref *nextthread,
372 threadref *threadlist));
374 typedef int (*rmt_thread_action) (threadref *ref, void *context);
376 static int remote_threadlist_iterator PARAMS ((rmt_thread_action stepfunction,
377 void *context, int looplimit));
379 static int remote_newthread_step PARAMS ((threadref *ref, void *context));
381 static int remote_current_thread PARAMS ((int oldpid));
383 int remote_find_new_threads PARAMS ((void));
385 static void record_currthread PARAMS ((int currthread));
387 static void init_remote_threads PARAMS ((void));
389 /* exported functions */
391 extern int fromhex PARAMS ((int a));
393 extern void getpkt PARAMS ((char *buf, int forever));
395 extern int putpkt PARAMS ((char *buf));
397 static int putpkt_binary PARAMS ((char *buf, int cnt));
399 void remote_console_output PARAMS ((char *));
401 static void check_binary_download PARAMS ((CORE_ADDR addr));
403 /* Define the target subroutine names */
405 void open_remote_target PARAMS ((char *, int, struct target_ops *, int));
407 void _initialize_remote PARAMS ((void));
411 static struct target_ops remote_ops;
413 static struct target_ops extended_remote_ops;
415 static struct target_thread_vector remote_thread_vec;
417 /* This was 5 seconds, which is a long time to sit and wait.
418 Unless this is going though some terminal server or multiplexer or
419 other form of hairy serial connection, I would think 2 seconds would
422 /* Changed to allow option to set timeout value.
423 was static int remote_timeout = 2; */
424 extern int remote_timeout;
426 /* This variable chooses whether to send a ^C or a break when the user
427 requests program interruption. Although ^C is usually what remote
428 systems expect, and that is the default here, sometimes a break is
429 preferable instead. */
431 static int remote_break;
433 /* Has the user attempted to interrupt the target? If so, then offer
434 the user the opportunity to bail out completely if he interrupts
436 static int interrupted_already = 0;
438 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
439 remote_open knows that we don't have a file open when the program
441 static serial_t remote_desc = NULL;
443 /* This variable (available to the user via "set remotebinarydownload")
444 dictates whether downloads are sent in binary (via the 'X' packet).
445 We assume that the stub can, and attempt to do it. This will be cleared if
446 the stub does not understand it. This switch is still needed, though
447 in cases when the packet is supported in the stub, but the connection
448 does not allow it (i.e., 7-bit serial connection only). */
449 static int remote_binary_download = 1;
451 /* Have we already checked whether binary downloads work? */
452 static int remote_binary_checked;
454 /* Having this larger than 400 causes us to be incompatible with m68k-stub.c
455 and i386-stub.c. Normally, no one would notice because it only matters
456 for writing large chunks of memory (e.g. in downloads). Also, this needs
457 to be more than 400 if required to hold the registers (see below, where
458 we round it up based on REGISTER_BYTES). */
461 /* Maximum number of bytes to read/write at once. The value here
462 is chosen to fill up a packet (the headers account for the 32). */
463 #define MAXBUFBYTES ((PBUFSIZ-32)/2)
465 /* Round up PBUFSIZ to hold all the registers, at least. */
466 /* The blank line after the #if seems to be required to work around a
467 bug in HP's PA compiler. */
468 #if REGISTER_BYTES > MAXBUFBYTES
471 #define PBUFSIZ (REGISTER_BYTES * 2 + 32)
474 /* This variable sets the number of bytes to be written to the target
475 in a single packet. Normally PBUFSIZ is satisfactory, but some
476 targets need smaller values (perhaps because the receiving end
479 static int remote_write_size = PBUFSIZ;
481 /* This variable sets the number of bits in an address that are to be
482 sent in a memory ("M" or "m") packet. Normally, after stripping
483 leading zeros, the entire address would be sent. This variable
484 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
485 initial implementation of remote.c restricted the address sent in
486 memory packets to ``host::sizeof long'' bytes - (typically 32
487 bits). Consequently, for 64 bit targets, the upper 32 bits of an
488 address was never sent. Since fixing this bug may cause a break in
489 some remote targets this variable is principly provided to
490 facilitate backward compatibility. */
492 static int remote_address_size;
494 /* This is the size (in chars) of the first response to the `g' command. This
495 is used to limit the size of the memory read and write commands to prevent
496 stub buffers from overflowing. The size does not include headers and
497 trailers, it is only the payload size. */
499 static int remote_register_buf_size = 0;
501 /* Should we try the 'P' request? If this is set to one when the stub
502 doesn't support 'P', the only consequence is some unnecessary traffic. */
503 static int stub_supports_P = 1;
505 /* These are pointers to hook functions that may be set in order to
506 modify resume/wait behavior for a particular architecture. */
508 void (*target_resume_hook) PARAMS ((void));
509 void (*target_wait_loop_hook) PARAMS ((void));
513 * Support for quasi-interactive control of device through GDB port.
514 * While we're waiting for an event to occur, chat with the running device.
519 extern int quit_flag;
521 static char tty_input[256];
522 static int escape_count;
523 static int echo_check;
524 static int remote_chat = 0;
532 static enum read_stat
538 /* Loop until the socket doesn't have any more data */
539 while ((data = readchar(0)) >= 0) {
541 /* Check for the escape sequence */
543 /* If this is the fourth escape, get out */
544 if (++escape_count == 4)
545 return (ENTER_DEBUG);
546 continue; /* Not the fourth, continue */
550 * Not an escape any more, Ensure any pending ones are flushed
552 for (j = 1; j <= escape_count; j++)
557 if (data == '\r') /* If this is a return character */
558 continue; /* just supress it */
560 if (echo_check != -1) { /* If we are checking for an echo */
561 /* If this might be an echo */
562 if (tty_input[echo_check] == data) {
563 echo_check++; /* Note one more character match */
564 continue; /* Go and loop */
567 if ((data == '\n') && (tty_input[echo_check] == '\r')) {
568 /* If this is the end of the line */
569 echo_check = -1; /* No more echo supression */
570 continue; /* Go and loop */
573 /* Not an echo, print out the data */
574 for (j = 0; j < echo_check; j++)
575 putchar(tty_input[j]);
577 echo_check = -1;/* No more echo checking */
580 putchar(data); /* Output the character */
582 return (READ_MORE); /* Indicate to read some more */
585 static enum read_stat
588 enum read_stat status;
591 /* First, read a buffer full from the terminal */
592 if ((tty_bc = read(fileno(stdin), tty_input, sizeof(tty_input) - 1)) < 0) {
593 perror_with_name("readtty: read failed");
594 return (FATAL_ERROR);
597 /* Turn trailing newlines into returns */
598 if (tty_input[tty_bc - 1] == '\n')
599 tty_input[tty_bc - 1] = '\r';
601 if ((tty_input[0] == '~') && (tty_bc == 3))
602 switch (tty_input[1]) {
603 case 'b': /* ~b\n = send break & gdb */
604 SERIAL_SEND_BREAK (remote_desc);
607 case 'c': /* ~c\n = return to gdb */
608 return (ENTER_DEBUG);
611 /* Make this a zero terminated string and write it out */
612 tty_input[tty_bc] = '\0';
614 if (SERIAL_WRITE(remote_desc, tty_input, tty_bc)) {
615 perror_with_name("readtty: write failed");
616 return (FATAL_ERROR);
627 enum read_stat status;
634 tablesize = getdtablesize();
639 * Check for anything from our socket - doesn't block. Note that this
640 * must be done *before* the select as there may be buffered I/O
641 * waiting to be processed.
643 if ((status = readtarget()) != READ_MORE)
646 fflush(stdout); /* Flush output before blocking */
648 /* Now block on more socket input or TTY input */
650 FD_SET(fileno(stdin), &input);
651 FD_SET(remote_desc->fd, &input);
653 status = select(tablesize, &input, 0, 0, 0);
654 if ((status < 0) && (errno != EINTR)) {
655 perror_with_name("remote_talk: select");
656 return (FATAL_ERROR);
659 /* Handle Control-C typed */
661 if ((++panic_flag) == 3) {
662 printf("\nAre you repeating Control-C to terminate "
663 "the session? (y/n) [n] ");
664 fgets(buf, 3, stdin);
666 pop_target(); /* Clean up */
667 error("Debugging terminated by user interrupt");
672 SERIAL_WRITE(remote_desc, "\003", 1);
676 /* Handle terminal input */
677 if (FD_ISSET(fileno(stdin), &input)) {
680 if (status != READ_MORE)
687 #endif /* REMOTE_CHAT */
689 /* These are the threads which we last sent to the remote system.
690 -1 for all or -2 for not sent yet. */
691 static int general_thread;
692 static int cont_thread;
694 /* Call this function as a result of
695 1) A halt indication (T packet) containing a thread id
696 2) A direct query of currthread
697 3) Successful execution of set thread
701 record_currthread (currthread)
704 #if 0 /* target_wait must not modify inferior_pid! */
705 inferior_pid = currthread;
707 general_thread = currthread;
708 #if 0 /* setting cont_thread has a different meaning
709 from having the target report its thread id. */
710 cont_thread = currthread;
712 /* If this is a new thread, add it to GDB's thread list.
713 If we leave it up to WFI to do this, bad things will happen. */
714 if (!in_thread_list (currthread))
715 add_thread (currthread);
718 #define MAGIC_NULL_PID 42000
726 int state = gen ? general_thread : cont_thread;
732 buf[1] = gen ? 'g' : 'c';
733 if (th == MAGIC_NULL_PID)
739 sprintf (&buf[2], "-%x", -th);
741 sprintf (&buf[2], "%x", th);
750 /* Return nonzero if the thread TH is still alive on the remote system. */
753 remote_thread_alive (th)
760 sprintf (&buf[1], "-%08x", -th);
762 sprintf (&buf[1], "%08x", th);
765 return (buf[0] == 'O' && buf[1] == 'K');
768 /* About these extended threadlist and threadinfo packets. They are
769 variable length packets but, the fields within them are often fixed
770 length. They are redundent enough to send over UDP as is the
771 remote protocol in general. There is a matching unit test module
774 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES*2)
776 /* encode 64 bits in 16 chars of hex */
778 static const char hexchars[] = "0123456789abcdef";
785 if ((ch >= 'a') && (ch <= 'f'))
787 *val = ch - 'a' + 10;
790 if ((ch >= 'A') && (ch <= 'F'))
792 *val = ch - 'A' + 10;
795 if ((ch >= '0') && (ch <= '9'))
807 if (ch >= 'a' && ch <= 'f')
808 return ch - 'a' + 10;
809 if (ch >= '0' && ch <= '9')
811 if (ch >= 'A' && ch <= 'F')
812 return ch - 'A' + 10;
817 stub_unpack_int (buff, fieldlength)
826 nibble = stubhex (*buff++);
830 retval = retval << 4;
836 unpack_varlen_hex (buff, result)
837 char *buff; /* packet to parse */
843 while (ishex (*buff, &nibble))
846 retval = retval << 4;
847 retval |= nibble & 0x0f;
854 unpack_nibble (buf, val)
863 pack_nibble (buf, nibble)
867 *buf++ = hexchars[(nibble & 0x0f)];
872 pack_hex_byte (pkt, byte)
876 *pkt++ = hexchars[(byte >> 4) & 0xf];
877 *pkt++ = hexchars[(byte & 0xf)];
882 unpack_byte (buf, value)
886 *value = stub_unpack_int (buf, 2);
891 pack_int (buf, value)
895 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
896 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
897 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
898 buf = pack_hex_byte (buf, (value & 0xff));
903 unpack_int (buf, value)
907 *value = stub_unpack_int (buf, 8);
911 #if 0 /* currently unused, uncomment when needed */
912 static char *pack_string PARAMS ((char *pkt, char *string));
915 pack_string (pkt, string)
922 len = strlen (string);
924 len = 200; /* Bigger than most GDB packets, junk??? */
925 pkt = pack_hex_byte (pkt, len);
929 if ((ch == '\0') || (ch == '#'))
930 ch = '*'; /* Protect encapsulation */
935 #endif /* 0 (unused) */
938 unpack_string (src, dest, length)
950 pack_threadid (pkt, id)
955 unsigned char *altid;
957 altid = (unsigned char *) id;
958 limit = pkt + BUF_THREAD_ID_SIZE;
960 pkt = pack_hex_byte (pkt, *altid++);
966 unpack_threadid (inbuf, id)
971 char *limit = inbuf + BUF_THREAD_ID_SIZE;
974 altref = (char *) id;
976 while (inbuf < limit)
978 x = stubhex (*inbuf++);
979 y = stubhex (*inbuf++);
980 *altref++ = (x << 4) | y;
985 /* Externally, threadrefs are 64 bits but internally, they are still
986 ints. This is due to a mismatch of specifications. We would like
987 to use 64bit thread references internally. This is an adapter
991 int_to_threadref (id, value)
997 scan = (unsigned char *) id;
1003 *scan++ = (value >> 24) & 0xff;
1004 *scan++ = (value >> 16) & 0xff;
1005 *scan++ = (value >> 8) & 0xff;
1006 *scan++ = (value & 0xff);
1010 threadref_to_int (ref)
1014 unsigned char *scan;
1016 scan = (char *) ref;
1020 value = (value << 8) | ((*scan++) & 0xff);
1025 copy_threadref (dest, src)
1030 unsigned char *csrc, *cdest;
1032 csrc = (unsigned char *) src;
1033 cdest = (unsigned char *) dest;
1040 threadmatch (dest, src)
1044 /* things are broken right now, so just assume we got a match */
1046 unsigned char *srcp, *destp;
1048 srcp = (char *) src;
1049 destp = (char *) dest;
1053 result &= (*srcp++ == *destp++) ? 1 : 0;
1060 threadid:1, # always request threadid
1067 /* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
1070 pack_threadinfo_request (pkt, mode, id)
1075 *pkt++ = 'q'; /* Info Query */
1076 *pkt++ = 'P'; /* process or thread info */
1077 pkt = pack_int (pkt, mode); /* mode */
1078 pkt = pack_threadid (pkt, id); /* threadid */
1079 *pkt = '\0'; /* terminate */
1083 /* These values tag the fields in a thread info response packet */
1084 /* Tagging the fields allows us to request specific fields and to
1085 add more fields as time goes by */
1087 #define TAG_THREADID 1 /* Echo the thread identifier */
1088 #define TAG_EXISTS 2 /* Is this process defined enough to
1089 fetch registers and its stack */
1090 #define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
1091 #define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is */
1092 #define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
1096 remote_unpack_thread_info_response (pkt, expectedref, info)
1098 threadref *expectedref;
1099 struct gdb_ext_thread_info *info;
1104 char *limit = pkt + PBUFSIZ; /* plausable parsing limit */
1107 /* info->threadid = 0; FIXME: implement zero_threadref */
1109 info->display[0] = '\0';
1110 info->shortname[0] = '\0';
1111 info->more_display[0] = '\0';
1113 /* Assume the characters indicating the packet type have been stripped */
1114 pkt = unpack_int (pkt, &mask); /* arg mask */
1115 pkt = unpack_threadid (pkt, &ref);
1118 warning ("Incomplete response to threadinfo request\n");
1119 if (!threadmatch (&ref, expectedref))
1120 { /* This is an answer to a different request */
1121 warning ("ERROR RMT Thread info mismatch\n");
1124 copy_threadref (&info->threadid, &ref);
1126 /* Loop on tagged fields , try to bail if somthing goes wrong */
1128 while ((pkt < limit) && mask && *pkt) /* packets are terminated with nulls */
1130 pkt = unpack_int (pkt, &tag); /* tag */
1131 pkt = unpack_byte (pkt, &length); /* length */
1132 if (!(tag & mask)) /* tags out of synch with mask */
1134 warning ("ERROR RMT: threadinfo tag mismatch\n");
1138 if (tag == TAG_THREADID)
1142 warning ("ERROR RMT: length of threadid is not 16\n");
1146 pkt = unpack_threadid (pkt, &ref);
1147 mask = mask & ~TAG_THREADID;
1150 if (tag == TAG_EXISTS)
1152 info->active = stub_unpack_int (pkt, length);
1154 mask = mask & ~(TAG_EXISTS);
1157 warning ("ERROR RMT: 'exists' length too long\n");
1163 if (tag == TAG_THREADNAME)
1165 pkt = unpack_string (pkt, &info->shortname[0], length);
1166 mask = mask & ~TAG_THREADNAME;
1169 if (tag == TAG_DISPLAY)
1171 pkt = unpack_string (pkt, &info->display[0], length);
1172 mask = mask & ~TAG_DISPLAY;
1175 if (tag == TAG_MOREDISPLAY)
1177 pkt = unpack_string (pkt, &info->more_display[0], length);
1178 mask = mask & ~TAG_MOREDISPLAY;
1181 warning ("ERROR RMT: unknown thread info tag\n");
1182 break; /* Not a tag we know about */
1188 remote_get_threadinfo (threadid, fieldset, info)
1189 threadref *threadid;
1190 int fieldset; /* TAG mask */
1191 struct gdb_ext_thread_info *info;
1194 char threadinfo_pkt[PBUFSIZ];
1196 pack_threadinfo_request (threadinfo_pkt, fieldset, threadid);
1197 putpkt (threadinfo_pkt);
1198 getpkt (threadinfo_pkt, 0);
1199 result = remote_unpack_thread_info_response (threadinfo_pkt + 2, threadid,
1204 /* Unfortunately, 61 bit thread-ids are bigger than the internal
1205 representation of a threadid. */
1208 adapt_remote_get_threadinfo (ref, selection, info)
1211 struct gdb_ext_thread_info *info;
1215 int_to_threadref (&lclref, *ref);
1216 return remote_get_threadinfo (&lclref, selection, info);
1219 /* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
1222 pack_threadlist_request (pkt, startflag, threadcount, nextthread)
1226 threadref *nextthread;
1228 *pkt++ = 'q'; /* info query packet */
1229 *pkt++ = 'L'; /* Process LIST or threadLIST request */
1230 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
1231 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
1232 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
1237 /* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
1240 parse_threadlist_response (pkt, result_limit, original_echo, resultlist,
1244 threadref *original_echo;
1245 threadref *resultlist;
1249 int count, resultcount, done;
1252 /* Assume the 'q' and 'M chars have been stripped. */
1253 limit = pkt + (PBUFSIZ - BUF_THREAD_ID_SIZE); /* done parse past here */
1254 pkt = unpack_byte (pkt, &count); /* count field */
1255 pkt = unpack_nibble (pkt, &done);
1256 /* The first threadid is the argument threadid. */
1257 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
1258 while ((count-- > 0) && (pkt < limit))
1260 pkt = unpack_threadid (pkt, resultlist++);
1261 if (resultcount++ >= result_limit)
1270 remote_get_threadlist (startflag, nextthread, result_limit,
1271 done, result_count, threadlist)
1273 threadref *nextthread;
1277 threadref *threadlist;
1280 static threadref echo_nextthread;
1281 char threadlist_packet[PBUFSIZ];
1282 char t_response[PBUFSIZ];
1285 /* Trancate result limit to be smaller than the packet size */
1286 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= PBUFSIZ)
1287 result_limit = (PBUFSIZ / BUF_THREAD_ID_SIZE) - 2;
1289 pack_threadlist_request (threadlist_packet,
1290 startflag, result_limit, nextthread);
1291 putpkt (threadlist_packet);
1292 getpkt (t_response, 0);
1295 parse_threadlist_response (t_response + 2, result_limit, &echo_nextthread,
1298 if (!threadmatch (&echo_nextthread, nextthread))
1300 /* FIXME: This is a good reason to drop the packet */
1301 /* Possably, there is a duplicate response */
1303 retransmit immediatly - race conditions
1304 retransmit after timeout - yes
1306 wait for packet, then exit
1308 warning ("HMM: threadlist did not echo arg thread, dropping it\n");
1309 return 0; /* I choose simply exiting */
1311 if (*result_count <= 0)
1315 warning ("RMT ERROR : failed to get remote thread list\n");
1318 return result; /* break; */
1320 if (*result_count > result_limit)
1323 warning ("RMT ERROR: threadlist response longer than requested\n");
1329 /* This is the interface between remote and threads, remotes upper interface */
1331 /* remote_find_new_threads retrieves the thread list and for each
1332 thread in the list, looks up the thread in GDB's internal list,
1333 ading the thread if it does not already exist. This involves
1334 getting partial thread lists from the remote target so, polling the
1335 quit_flag is required. */
1338 /* About this many threadisds fit in a packet. */
1340 #define MAXTHREADLISTRESULTS 32
1343 remote_threadlist_iterator (stepfunction, context, looplimit)
1344 rmt_thread_action stepfunction;
1348 int done, i, result_count;
1352 static threadref nextthread;
1353 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
1358 if (loopcount++ > looplimit)
1361 warning ("Remote fetch threadlist -infinite loop-\n");
1364 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
1365 &done, &result_count, resultthreadlist))
1370 /* clear for later iterations */
1372 /* Setup to resume next batch of thread references, set nextthread. */
1373 if (result_count >= 1)
1374 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
1376 while (result_count--)
1377 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
1384 remote_newthread_step (ref, context)
1390 pid = threadref_to_int (ref);
1391 if (!in_thread_list (pid))
1393 return 1; /* continue iterator */
1396 #define CRAZY_MAX_THREADS 1000
1399 remote_current_thread (oldpid)
1406 if (buf[0] == 'Q' && buf[1] == 'C')
1407 return strtol (&buf[2], NULL, 16);
1413 remote_find_new_threads ()
1417 ret = remote_threadlist_iterator (remote_newthread_step, 0,
1419 if (inferior_pid == MAGIC_NULL_PID) /* ack ack ack */
1420 inferior_pid = remote_current_thread (inferior_pid);
1424 /* Initialize the thread vector which is used by threads.c */
1425 /* The thread stub is a package, it has an initializer */
1428 init_remote_threads ()
1430 remote_thread_vec.find_new_threads = remote_find_new_threads;
1431 remote_thread_vec.get_thread_info = adapt_remote_get_threadinfo;
1435 /* Restart the remote side; this is an extended protocol operation. */
1438 extended_remote_restart ()
1442 /* Send the restart command; for reasons I don't understand the
1443 remote side really expects a number after the "R". */
1445 sprintf (&buf[1], "%x", 0);
1448 /* Now query for status so this looks just like we restarted
1449 gdbserver from scratch. */
1454 /* Clean up connection to a remote debugger. */
1458 remote_close (quitting)
1462 SERIAL_CLOSE (remote_desc);
1466 /* Query the remote side for the text, data and bss offsets. */
1471 char buf[PBUFSIZ], *ptr;
1473 CORE_ADDR text_addr, data_addr, bss_addr;
1474 struct section_offsets *offs;
1478 (void) remote_talk();
1479 #endif /* REMOTE_CHAT */
1481 putpkt ("qOffsets");
1485 if (buf[0] == '\000')
1486 return; /* Return silently. Stub doesn't support
1490 warning ("Remote failure reply: %s", buf);
1494 /* Pick up each field in turn. This used to be done with scanf, but
1495 scanf will make trouble if CORE_ADDR size doesn't match
1496 conversion directives correctly. The following code will work
1497 with any size of CORE_ADDR. */
1498 text_addr = data_addr = bss_addr = 0;
1502 if (strncmp (ptr, "Text=", 5) == 0)
1505 /* Don't use strtol, could lose on big values. */
1506 while (*ptr && *ptr != ';')
1507 text_addr = (text_addr << 4) + fromhex (*ptr++);
1512 if (!lose && strncmp (ptr, ";Data=", 6) == 0)
1515 while (*ptr && *ptr != ';')
1516 data_addr = (data_addr << 4) + fromhex (*ptr++);
1521 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
1524 while (*ptr && *ptr != ';')
1525 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
1531 error ("Malformed response to offset query, %s", buf);
1533 if (symfile_objfile == NULL)
1536 offs = (struct section_offsets *) alloca (sizeof (struct section_offsets)
1537 + symfile_objfile->num_sections
1538 * sizeof (offs->offsets));
1539 memcpy (offs, symfile_objfile->section_offsets,
1540 sizeof (struct section_offsets)
1541 + symfile_objfile->num_sections
1542 * sizeof (offs->offsets));
1544 ANOFFSET (offs, SECT_OFF_TEXT) = text_addr;
1546 /* This is a temporary kludge to force data and bss to use the same offsets
1547 because that's what nlmconv does now. The real solution requires changes
1548 to the stub and remote.c that I don't have time to do right now. */
1550 ANOFFSET (offs, SECT_OFF_DATA) = data_addr;
1551 ANOFFSET (offs, SECT_OFF_BSS) = data_addr;
1553 objfile_relocate (symfile_objfile, offs);
1556 /* Stub for catch_errors. */
1559 remote_start_remote (dummy)
1562 immediate_quit = 1; /* Allow user to interrupt it */
1564 /* Ack any packet which the remote side has already sent. */
1565 SERIAL_WRITE (remote_desc, "+", 1);
1567 /* Let the stub know that we want it to return the thread. */
1570 inferior_pid = remote_current_thread (inferior_pid);
1572 get_offsets (); /* Get text, data & bss offsets */
1574 putpkt ("?"); /* initiate a query from remote machine */
1577 start_remote (); /* Initialize gdb process mechanisms */
1581 /* Open a connection to a remote debugger.
1582 NAME is the filename used for communication. */
1585 remote_open (name, from_tty)
1589 remote_open_1 (name, from_tty, &remote_ops, 0);
1592 /* Open a connection to a remote debugger using the extended
1593 remote gdb protocol. NAME is the filename used for communication. */
1596 extended_remote_open (name, from_tty)
1600 remote_open_1 (name, from_tty, &extended_remote_ops, 1/*extended_p*/);
1603 /* Generic code for opening a connection to a remote target. */
1605 static DCACHE *remote_dcache;
1608 remote_open_1 (name, from_tty, target, extended_p)
1611 struct target_ops *target;
1615 error ("To open a remote debug connection, you need to specify what\n\
1616 serial device is attached to the remote system (e.g. /dev/ttya).");
1618 target_preopen (from_tty);
1620 unpush_target (target);
1622 remote_dcache = dcache_init (remote_read_bytes, remote_write_bytes);
1624 remote_desc = SERIAL_OPEN (name);
1626 perror_with_name (name);
1628 if (baud_rate != -1)
1630 if (SERIAL_SETBAUDRATE (remote_desc, baud_rate))
1632 SERIAL_CLOSE (remote_desc);
1633 perror_with_name (name);
1638 SERIAL_RAW (remote_desc);
1640 /* If there is something sitting in the buffer we might take it as a
1641 response to a command, which would be bad. */
1642 SERIAL_FLUSH_INPUT (remote_desc);
1646 puts_filtered ("Remote debugging using ");
1647 puts_filtered (name);
1648 puts_filtered ("\n");
1650 push_target (target); /* Switch to using remote target now */
1652 /* The target vector does not have the thread functions in it yet,
1653 so we use this function to call back into the thread module and
1654 register the thread vector and its contained functions. */
1655 bind_target_thread_vector (&remote_thread_vec);
1657 /* Start out by trying the 'P' request to set registers. We set
1658 this each time that we open a new target so that if the user
1659 switches from one stub to another, we can (if the target is
1660 closed and reopened) cope. */
1661 stub_supports_P = 1;
1663 general_thread = -2;
1666 /* Force remote_write_bytes to check whether target supports
1667 binary downloading. */
1668 remote_binary_checked = 0;
1670 /* Without this, some commands which require an active target (such
1671 as kill) won't work. This variable serves (at least) double duty
1672 as both the pid of the target process (if it has such), and as a
1673 flag indicating that a target is active. These functions should
1674 be split out into seperate variables, especially since GDB will
1675 someday have a notion of debugging several processes. */
1677 inferior_pid = MAGIC_NULL_PID;
1678 /* Start the remote connection; if error (0), discard this target.
1679 In particular, if the user quits, be sure to discard it
1680 (we'd be in an inconsistent state otherwise). */
1681 if (!catch_errors (remote_start_remote, NULL,
1682 "Couldn't establish connection to remote target\n",
1691 /* tell the remote that we're using the extended protocol. */
1698 /* This takes a program previously attached to and detaches it. After
1699 this is done, GDB can be used to debug some other program. We
1700 better not have left any breakpoints in the target program or it'll
1701 die when it hits one. */
1704 remote_detach (args, from_tty)
1711 error ("Argument given to \"detach\" when remotely debugging.");
1713 /* Tell the remote target to detach. */
1719 puts_filtered ("Ending remote debugging.\n");
1722 /* Convert hex digit A to a number. */
1728 if (a >= '0' && a <= '9')
1730 else if (a >= 'a' && a <= 'f')
1731 return a - 'a' + 10;
1732 else if (a >= 'A' && a <= 'F')
1733 return a - 'A' + 10;
1735 error ("Reply contains invalid hex digit %d", a);
1738 /* Convert number NIB to a hex digit. */
1750 /* Tell the remote machine to resume. */
1752 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
1754 static int last_sent_step;
1757 remote_resume (pid, step, siggnal)
1759 enum target_signal siggnal;
1764 set_thread (0, 0); /* run any thread */
1766 set_thread (pid, 0); /* run this thread */
1768 dcache_flush (remote_dcache);
1770 last_sent_signal = siggnal;
1771 last_sent_step = step;
1773 /* A hook for when we need to do something at the last moment before
1775 if (target_resume_hook)
1776 (*target_resume_hook) ();
1778 if (siggnal != TARGET_SIGNAL_0)
1780 buf[0] = step ? 'S' : 'C';
1781 buf[1] = tohex (((int)siggnal >> 4) & 0xf);
1782 buf[2] = tohex ((int)siggnal & 0xf);
1786 strcpy (buf, step ? "s": "c");
1791 /* Send ^C to target to halt it. Target will respond, and send us a
1794 static void (*ofunc) PARAMS ((int));
1797 remote_interrupt (signo)
1801 signal (signo, remote_interrupt);
1807 if (!interrupted_already)
1809 /* Send a break or a ^C, depending on user preference. */
1810 interrupted_already = 1;
1813 printf_unfiltered ("remote_stop called\n");
1816 SERIAL_SEND_BREAK (remote_desc);
1818 SERIAL_WRITE (remote_desc, "\003", 1);
1822 signal (SIGINT, ofunc);
1824 signal (SIGINT, remote_interrupt);
1825 interrupted_already = 0;
1829 /* Ask the user what to do when an interrupt is received. */
1834 target_terminal_ours ();
1836 if (query ("Interrupted while waiting for the program.\n\
1837 Give up (and stop debugging it)? "))
1839 target_mourn_inferior ();
1840 return_to_top_level (RETURN_QUIT);
1843 target_terminal_inferior ();
1846 /* If nonzero, ignore the next kill. */
1851 remote_console_output (msg)
1856 for (p = msg; *p; p +=2)
1859 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
1862 if (target_output_hook)
1863 target_output_hook (tb);
1865 fputs_filtered (tb, gdb_stdout);
1869 /* Wait until the remote machine stops, then return, storing status in
1870 STATUS just as `wait' would. Returns "pid" (though it's not clear
1871 what, if anything, that means in the case of this target). */
1874 remote_wait (pid, status)
1876 struct target_waitstatus *status;
1878 unsigned char buf[PBUFSIZ];
1879 int thread_num = -1;
1881 status->kind = TARGET_WAITKIND_EXITED;
1882 status->value.integer = 0;
1890 (void) remote_talk();
1891 #endif /* REMOTE_CHAT */
1893 interrupted_already = 0;
1894 ofunc = signal (SIGINT, remote_interrupt);
1895 getpkt ((char *) buf, 1);
1896 signal (SIGINT, ofunc);
1898 /* This is a hook for when we need to do something (perhaps the
1899 collection of trace data) every time the target stops. */
1900 if (target_wait_loop_hook)
1901 (*target_wait_loop_hook) ();
1905 case 'E': /* Error of some sort */
1906 warning ("Remote failure reply: %s", buf);
1908 case 'T': /* Status with PC, SP, FP, ... */
1912 char regs[MAX_REGISTER_RAW_SIZE];
1914 /* Expedited reply, containing Signal, {regno, reg} repeat */
1915 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
1917 n... = register number
1918 r... = register contents
1920 p = &buf[3]; /* after Txx */
1927 /* Read the register number */
1928 regno = strtol ((const char *) p, &p_temp, 16);
1929 p1 = (unsigned char *)p_temp;
1931 if (p1 == p) /* No register number present here */
1933 p1 = (unsigned char *) strchr ((const char *) p, ':');
1935 warning ("Malformed packet(a) (missing colon): %s\n\
1938 if (strncmp ((const char *) p, "thread", p1 - p) == 0)
1940 p_temp = unpack_varlen_hex (++p1, &thread_num);
1941 record_currthread (thread_num);
1942 p = (unsigned char *) p_temp;
1950 warning ("Malformed packet(b) (missing colon): %s\n\
1954 if (regno >= NUM_REGS)
1955 warning ("Remote sent bad register number %ld: %s\n\
1959 for (i = 0; i < REGISTER_RAW_SIZE (regno); i++)
1961 if (p[0] == 0 || p[1] == 0)
1962 warning ("Remote reply is too short: %s", buf);
1963 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
1966 supply_register (regno, regs);
1971 warning ("Remote register badly formatted: %s", buf);
1972 warning (" here: %s",p);
1977 case 'S': /* Old style status, just signal only */
1978 status->kind = TARGET_WAITKIND_STOPPED;
1979 status->value.sig = (enum target_signal)
1980 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
1983 case 'W': /* Target exited */
1985 /* The remote process exited. */
1986 status->kind = TARGET_WAITKIND_EXITED;
1987 status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
1991 status->kind = TARGET_WAITKIND_SIGNALLED;
1992 status->value.sig = (enum target_signal)
1993 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
1997 case 'O': /* Console output */
1998 remote_console_output (buf + 1);
2001 if (last_sent_signal != TARGET_SIGNAL_0)
2003 /* Zero length reply means that we tried 'S' or 'C' and
2004 the remote system doesn't support it. */
2005 target_terminal_ours_for_output ();
2007 ("Can't send signals to this remote system. %s not sent.\n",
2008 target_signal_to_name (last_sent_signal));
2009 last_sent_signal = TARGET_SIGNAL_0;
2010 target_terminal_inferior ();
2012 strcpy ((char *) buf, last_sent_step ? "s" : "c");
2013 putpkt ((char *) buf);
2016 /* else fallthrough */
2018 warning ("Invalid remote reply: %s", buf);
2023 if (thread_num != -1)
2025 /* Initial thread value can only be acquired via wait, so deal with
2026 this marker which is used before the first thread value is
2028 if (inferior_pid == MAGIC_NULL_PID)
2030 inferior_pid = thread_num;
2031 if (!in_thread_list (inferior_pid))
2032 add_thread (inferior_pid);
2036 return inferior_pid;
2039 /* Number of bytes of registers this stub implements. */
2041 static int register_bytes_found;
2043 /* Read the remote registers into the block REGS. */
2044 /* Currently we just read all the registers, so we don't use regno. */
2048 remote_fetch_registers (regno)
2054 char regs[REGISTER_BYTES];
2056 set_thread (inferior_pid, 1);
2061 if (remote_register_buf_size == 0)
2062 remote_register_buf_size = strlen (buf);
2064 /* Unimplemented registers read as all bits zero. */
2065 memset (regs, 0, REGISTER_BYTES);
2067 /* We can get out of synch in various cases. If the first character
2068 in the buffer is not a hex character, assume that has happened
2069 and try to fetch another packet to read. */
2070 while ((buf[0] < '0' || buf[0] > '9')
2071 && (buf[0] < 'a' || buf[0] > 'f')
2072 && buf[0] != 'x') /* New: unavailable register value */
2075 printf_unfiltered ("Bad register packet; fetching a new packet\n");
2079 /* Reply describes registers byte by byte, each byte encoded as two
2080 hex characters. Suck them all up, then supply them to the
2081 register cacheing/storage mechanism. */
2084 for (i = 0; i < REGISTER_BYTES; i++)
2090 warning ("Remote reply is of odd length: %s", buf);
2091 /* Don't change register_bytes_found in this case, and don't
2092 print a second warning. */
2095 if (p[0] == 'x' && p[1] == 'x')
2096 regs[i] = 0; /* 'x' */
2098 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
2102 if (i != register_bytes_found)
2104 register_bytes_found = i;
2105 #ifdef REGISTER_BYTES_OK
2106 if (!REGISTER_BYTES_OK (i))
2107 warning ("Remote reply is too short: %s", buf);
2112 for (i = 0; i < NUM_REGS; i++)
2114 supply_register (i, ®s[REGISTER_BYTE(i)]);
2115 if (buf[REGISTER_BYTE(i) * 2] == 'x')
2116 register_valid[i] = -1; /* register value not available */
2120 /* Prepare to store registers. Since we may send them all (using a
2121 'G' request), we have to read out the ones we don't want to change
2125 remote_prepare_to_store ()
2127 /* Make sure the entire registers array is valid. */
2128 read_register_bytes (0, (char *)NULL, REGISTER_BYTES);
2131 /* Store register REGNO, or all registers if REGNO == -1, from the contents
2132 of REGISTERS. FIXME: ignores errors. */
2135 remote_store_registers (regno)
2142 set_thread (inferior_pid, 1);
2144 if (regno >= 0 && stub_supports_P)
2146 /* Try storing a single register. */
2149 sprintf (buf, "P%x=", regno);
2150 p = buf + strlen (buf);
2151 regp = ®isters[REGISTER_BYTE (regno)];
2152 for (i = 0; i < REGISTER_RAW_SIZE (regno); ++i)
2154 *p++ = tohex ((regp[i] >> 4) & 0xf);
2155 *p++ = tohex (regp[i] & 0xf);
2161 /* The stub understands the 'P' request. We are done. */
2165 /* The stub does not support the 'P' request. Use 'G' instead,
2166 and don't try using 'P' in the future (it will just waste our
2168 stub_supports_P = 0;
2173 /* Command describes registers byte by byte,
2174 each byte encoded as two hex characters. */
2177 /* remote_prepare_to_store insures that register_bytes_found gets set. */
2178 for (i = 0; i < register_bytes_found; i++)
2180 *p++ = tohex ((registers[i] >> 4) & 0xf);
2181 *p++ = tohex (registers[i] & 0xf);
2188 /* Use of the data cache *used* to be disabled because it loses for looking
2189 at and changing hardware I/O ports and the like. Accepting `volatile'
2190 would perhaps be one way to fix it. Another idea would be to use the
2191 executable file for the text segment (for all SEC_CODE sections?
2192 For all SEC_READONLY sections?). This has problems if you want to
2193 actually see what the memory contains (e.g. self-modifying code,
2194 clobbered memory, user downloaded the wrong thing).
2196 Because it speeds so much up, it's now enabled, if you're playing
2197 with registers you turn it of (set remotecache 0). */
2199 /* Read a word from remote address ADDR and return it.
2200 This goes through the data cache. */
2204 remote_fetch_word (addr)
2207 return dcache_fetch (remote_dcache, addr);
2210 /* Write a word WORD into remote address ADDR.
2211 This goes through the data cache. */
2214 remote_store_word (addr, word)
2218 dcache_poke (remote_dcache, addr, word);
2220 #endif /* 0 (unused?) */
2224 /* Return the number of hex digits in num. */
2232 for (i = 0; num != 0; i++)
2238 /* Set BUF to the hex digits representing NUM. */
2241 hexnumstr (buf, num)
2246 int len = hexnumlen (num);
2250 for (i = len - 1; i >= 0; i--)
2252 buf[i] = "0123456789abcdef" [(num & 0xf)];
2259 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
2262 remote_address_masked (addr)
2265 if (remote_address_size > 0
2266 && remote_address_size < (sizeof (ULONGEST) * 8))
2268 /* Only create a mask when that mask can safely be constructed
2269 in a ULONGEST variable. */
2271 mask = (mask << remote_address_size) - 1;
2277 /* Determine whether the remote target supports binary downloading.
2278 This is accomplished by sending a no-op memory write of zero length
2279 to the target at the specified address. It does not suffice to send
2280 the whole packet, since many stubs strip the eighth bit and subsequently
2281 compute a wrong checksum, which causes real havoc with remote_write_bytes. */
2283 check_binary_download (addr)
2286 if (remote_binary_download && !remote_binary_checked)
2288 char buf[PBUFSIZ], *p;
2289 remote_binary_checked = 1;
2293 p += hexnumstr (p, (ULONGEST) addr);
2295 p += hexnumstr (p, (ULONGEST) 0);
2299 putpkt_binary (buf, (int) (p - buf));
2303 remote_binary_download = 0;
2308 if (remote_binary_download)
2309 printf_unfiltered ("binary downloading suppported by target\n");
2311 printf_unfiltered ("binary downloading NOT suppported by target\n");
2315 /* Write memory data directly to the remote machine.
2316 This does not inform the data cache; the data cache uses this.
2317 MEMADDR is the address in the remote memory space.
2318 MYADDR is the address of the buffer in our space.
2319 LEN is the number of bytes.
2321 Returns number of bytes transferred, or 0 for error. */
2324 remote_write_bytes (memaddr, myaddr, len)
2329 int max_buf_size; /* Max size of packet output buffer */
2332 /* Verify that the target can support a binary download */
2333 check_binary_download (memaddr);
2335 /* Chop the transfer down if necessary */
2337 max_buf_size = min (remote_write_size, PBUFSIZ);
2338 if (remote_register_buf_size != 0)
2339 max_buf_size = min (max_buf_size, remote_register_buf_size);
2341 /* Subtract header overhead from max payload size - $M<memaddr>,<len>:#nn */
2342 max_buf_size -= 2 + hexnumlen (memaddr + len - 1) + 1 + hexnumlen (len) + 4;
2347 unsigned char buf[PBUFSIZ];
2348 unsigned char *p, *plen;
2352 /* construct "M"<memaddr>","<len>":" */
2353 /* sprintf (buf, "M%lx,%x:", (unsigned long) memaddr, todo); */
2354 memaddr = remote_address_masked (memaddr);
2356 if (remote_binary_download)
2359 todo = min (len, max_buf_size);
2364 todo = min (len, max_buf_size / 2); /* num bytes that will fit */
2367 p += hexnumstr (p, (ULONGEST) memaddr);
2370 plen = p; /* remember where len field goes */
2371 p += hexnumstr (p, (ULONGEST) todo);
2375 /* We send target system values byte by byte, in increasing byte
2376 addresses, each byte encoded as two hex characters (or one
2377 binary character). */
2378 if (remote_binary_download)
2382 (i < todo) && (i + escaped) < (max_buf_size - 2);
2385 switch (myaddr[i] & 0xff)
2390 /* These must be escaped */
2393 *p++ = (myaddr[i] & 0xff) ^ 0x20;
2396 *p++ = myaddr[i] & 0xff;
2403 /* Escape chars have filled up the buffer prematurely,
2404 and we have actually sent fewer bytes than planned.
2405 Fix-up the length field of the packet. */
2407 /* FIXME: will fail if new len is a shorter string than
2410 plen += hexnumstr (plen, (ULONGEST) i);
2416 for (i = 0; i < todo; i++)
2418 *p++ = tohex ((myaddr[i] >> 4) & 0xf);
2419 *p++ = tohex (myaddr[i] & 0xf);
2424 putpkt_binary (buf, (int) (p - buf));
2429 /* There is no correspondance between what the remote protocol uses
2430 for errors and errno codes. We would like a cleaner way of
2431 representing errors (big enough to include errno codes, bfd_error
2432 codes, and others). But for now just return EIO. */
2437 /* Increment by i, not by todo, in case escape chars
2438 caused us to send fewer bytes than we'd planned. */
2446 /* Read memory data directly from the remote machine.
2447 This does not use the data cache; the data cache uses this.
2448 MEMADDR is the address in the remote memory space.
2449 MYADDR is the address of the buffer in our space.
2450 LEN is the number of bytes.
2452 Returns number of bytes transferred, or 0 for error. */
2455 remote_read_bytes (memaddr, myaddr, len)
2460 int max_buf_size; /* Max size of packet output buffer */
2463 /* Chop the transfer down if necessary */
2465 max_buf_size = min (remote_write_size, PBUFSIZ);
2466 if (remote_register_buf_size != 0)
2467 max_buf_size = min (max_buf_size, remote_register_buf_size);
2477 todo = min (len, max_buf_size / 2); /* num bytes that will fit */
2479 /* construct "m"<memaddr>","<len>" */
2480 /* sprintf (buf, "m%lx,%x", (unsigned long) memaddr, todo); */
2481 memaddr = remote_address_masked (memaddr);
2484 p += hexnumstr (p, (ULONGEST) memaddr);
2486 p += hexnumstr (p, (ULONGEST) todo);
2494 /* There is no correspondance between what the remote protocol uses
2495 for errors and errno codes. We would like a cleaner way of
2496 representing errors (big enough to include errno codes, bfd_error
2497 codes, and others). But for now just return EIO. */
2502 /* Reply describes memory byte by byte,
2503 each byte encoded as two hex characters. */
2506 for (i = 0; i < todo; i++)
2508 if (p[0] == 0 || p[1] == 0)
2509 /* Reply is short. This means that we were able to read
2510 only part of what we wanted to. */
2511 return i + (origlen - len);
2512 myaddr[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
2522 /* Read or write LEN bytes from inferior memory at MEMADDR,
2523 transferring to or from debugger address MYADDR. Write to inferior
2524 if SHOULD_WRITE is nonzero. Returns length of data written or
2525 read; 0 for error. */
2529 remote_xfer_memory (memaddr, myaddr, len, should_write, target)
2534 struct target_ops *target; /* ignored */
2536 #ifdef REMOTE_TRANSLATE_XFER_ADDRESS
2539 REMOTE_TRANSLATE_XFER_ADDRESS (memaddr, len, targaddr, targlen);
2546 return dcache_xfer_memory (remote_dcache, memaddr, myaddr,
2552 /* Enable after 4.12. */
2555 remote_search (len, data, mask, startaddr, increment, lorange, hirange
2556 addr_found, data_found)
2560 CORE_ADDR startaddr;
2564 CORE_ADDR *addr_found;
2567 if (increment == -4 && len == 4)
2569 long mask_long, data_long;
2570 long data_found_long;
2571 CORE_ADDR addr_we_found;
2573 long returned_long[2];
2576 mask_long = extract_unsigned_integer (mask, len);
2577 data_long = extract_unsigned_integer (data, len);
2578 sprintf (buf, "t%x:%x,%x", startaddr, data_long, mask_long);
2583 /* The stub doesn't support the 't' request. We might want to
2584 remember this fact, but on the other hand the stub could be
2585 switched on us. Maybe we should remember it only until
2586 the next "target remote". */
2587 generic_search (len, data, mask, startaddr, increment, lorange,
2588 hirange, addr_found, data_found);
2593 /* There is no correspondance between what the remote protocol uses
2594 for errors and errno codes. We would like a cleaner way of
2595 representing errors (big enough to include errno codes, bfd_error
2596 codes, and others). But for now just use EIO. */
2597 memory_error (EIO, startaddr);
2600 while (*p != '\0' && *p != ',')
2601 addr_we_found = (addr_we_found << 4) + fromhex (*p++);
2603 error ("Protocol error: short return for search");
2605 data_found_long = 0;
2606 while (*p != '\0' && *p != ',')
2607 data_found_long = (data_found_long << 4) + fromhex (*p++);
2608 /* Ignore anything after this comma, for future extensions. */
2610 if (addr_we_found < lorange || addr_we_found >= hirange)
2616 *addr_found = addr_we_found;
2617 *data_found = store_unsigned_integer (data_we_found, len);
2620 generic_search (len, data, mask, startaddr, increment, lorange,
2621 hirange, addr_found, data_found);
2626 remote_files_info (ignore)
2627 struct target_ops *ignore;
2629 puts_filtered ("Debugging a target over a serial line.\n");
2632 /* Stuff for dealing with the packets which are part of this protocol.
2633 See comment at top of file for details. */
2635 /* Read a single character from the remote end, masking it down to 7 bits. */
2643 ch = SERIAL_READCHAR (remote_desc, timeout);
2648 error ("Remote connection closed");
2650 perror_with_name ("Remote communication error");
2651 case SERIAL_TIMEOUT:
2658 /* Send the command in BUF to the remote machine, and read the reply
2659 into BUF. Report an error if we get an error reply. */
2669 error ("Remote failure reply: %s", buf);
2672 /* Display a null-terminated packet on stdout, for debugging, using C
2679 puts_filtered ("\"");
2681 gdb_printchar (*buf++, gdb_stdout, '"');
2682 puts_filtered ("\"");
2689 return putpkt_binary (buf, strlen (buf));
2692 /* Send a packet to the remote machine, with error checking. The data
2693 of the packet is in BUF. The string in BUF can be at most PBUFSIZ - 5
2694 to account for the $, # and checksum, and for a possible /0 if we are
2695 debugging (remote_debug) and want to print the sent packet as a string */
2698 putpkt_binary (buf, cnt)
2703 unsigned char csum = 0;
2709 /* Copy the packet into buffer BUF2, encapsulating it
2710 and giving it a checksum. */
2712 if (cnt > (int) sizeof (buf2) - 5) /* Prosanity check */
2718 for (i = 0; i < cnt; i++)
2724 *p++ = tohex ((csum >> 4) & 0xf);
2725 *p++ = tohex (csum & 0xf);
2727 /* Send it over and over until we get a positive ack. */
2731 int started_error_output = 0;
2736 printf_unfiltered ("Sending packet: %s...", buf2);
2737 gdb_flush (gdb_stdout);
2739 if (SERIAL_WRITE (remote_desc, buf2, p - buf2))
2740 perror_with_name ("putpkt: write failed");
2742 /* read until either a timeout occurs (-2) or '+' is read */
2745 ch = readchar (remote_timeout);
2752 case SERIAL_TIMEOUT:
2754 if (started_error_output)
2756 putchar_unfiltered ('\n');
2757 started_error_output = 0;
2766 printf_unfiltered ("Ack\n");
2768 case SERIAL_TIMEOUT:
2772 break; /* Retransmit buffer */
2775 char junkbuf[PBUFSIZ];
2777 /* It's probably an old response, and we're out of sync.
2778 Just gobble up the packet and ignore it. */
2779 getpkt (junkbuf, 0);
2780 continue; /* Now, go look for + */
2786 if (!started_error_output)
2788 /* else fall through */
2790 #endif /* REMOTE_CHAT */
2795 if (!started_error_output)
2797 started_error_output = 1;
2798 printf_unfiltered ("putpkt: Junk: ");
2800 putchar_unfiltered (ch & 0177);
2804 break; /* Here to retransmit */
2808 /* This is wrong. If doing a long backtrace, the user should be
2809 able to get out next time we call QUIT, without anything as
2810 violent as interrupt_query. If we want to provide a way out of
2811 here without getting to the next QUIT, it should be based on
2812 hitting ^C twice as in remote_wait. */
2822 /* Come here after finding the start of the frame. Collect the rest
2823 into BUF, verifying the checksum, length, and handling run-length
2824 compression. Returns 0 on any error, 1 on success. */
2839 c = readchar (remote_timeout);
2843 case SERIAL_TIMEOUT:
2845 puts_filtered ("Timeout in mid-packet, retrying\n");
2849 puts_filtered ("Saw new packet start in middle of old one\n");
2850 return 0; /* Start a new packet, count retries */
2853 unsigned char pktcsum;
2857 pktcsum = fromhex (readchar (remote_timeout)) << 4;
2858 pktcsum |= fromhex (readchar (remote_timeout));
2860 if (csum == pktcsum)
2865 printf_filtered ("Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
2867 puts_filtered (buf);
2868 puts_filtered ("\n");
2872 case '*': /* Run length encoding */
2874 c = readchar (remote_timeout);
2876 c = c - ' ' + 3; /* Compute repeat count */
2879 if (c > 0 && c < 255 && bp + c - 1 < buf + PBUFSIZ - 1)
2881 memset (bp, *(bp - 1), c);
2887 printf_filtered ("Repeat count %d too large for buffer: ", c);
2888 puts_filtered (buf);
2889 puts_filtered ("\n");
2893 if (bp < buf + PBUFSIZ - 1)
2901 puts_filtered ("Remote packet too long: ");
2902 puts_filtered (buf);
2903 puts_filtered ("\n");
2910 /* Read a packet from the remote machine, with error checking, and
2911 store it in BUF. BUF is expected to be of size PBUFSIZ. If
2912 FOREVER, wait forever rather than timing out; this is used while
2913 the target is executing user code. */
2916 getpkt (buf, forever)
2925 strcpy (buf,"timeout");
2929 #ifdef MAINTENANCE_CMDS
2930 timeout = watchdog > 0 ? watchdog : -1;
2937 timeout = remote_timeout;
2941 for (tries = 1; tries <= MAX_TRIES; tries++)
2943 /* This can loop forever if the remote side sends us characters
2944 continuously, but if it pauses, we'll get a zero from readchar
2945 because of timeout. Then we'll count that as a retry. */
2947 /* Note that we will only wait forever prior to the start of a packet.
2948 After that, we expect characters to arrive at a brisk pace. They
2949 should show up within remote_timeout intervals. */
2953 c = readchar (timeout);
2955 if (c == SERIAL_TIMEOUT)
2957 #ifdef MAINTENANCE_CMDS
2958 if (forever) /* Watchdog went off. Kill the target. */
2960 target_mourn_inferior ();
2961 error ("Watchdog has expired. Target detached.\n");
2965 puts_filtered ("Timed out.\n");
2971 /* We've found the start of a packet, now collect the data. */
2973 val = read_frame (buf);
2978 fprintf_unfiltered (gdb_stdout, "Packet received: %s\n", buf);
2979 SERIAL_WRITE (remote_desc, "+", 1);
2983 /* Try the whole thing again. */
2985 SERIAL_WRITE (remote_desc, "-", 1);
2988 /* We have tried hard enough, and just can't receive the packet. Give up. */
2990 printf_unfiltered ("Ignoring packet error, continuing...\n");
2991 SERIAL_WRITE (remote_desc, "+", 1);
2997 /* For some mysterious reason, wait_for_inferior calls kill instead of
2998 mourn after it gets TARGET_WAITKIND_SIGNALLED. Work around it. */
3002 target_mourn_inferior ();
3006 /* Use catch_errors so the user can quit from gdb even when we aren't on
3007 speaking terms with the remote system. */
3008 catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
3010 /* Don't wait for it to die. I'm not really sure it matters whether
3011 we do or not. For the existing stubs, kill is a noop. */
3012 target_mourn_inferior ();
3018 remote_mourn_1 (&remote_ops);
3022 extended_remote_mourn ()
3024 /* We do _not_ want to mourn the target like this; this will
3025 remove the extended remote target from the target stack,
3026 and the next time the user says "run" it'll fail.
3028 FIXME: What is the right thing to do here? */
3030 remote_mourn_1 (&extended_remote_ops);
3034 /* Worker function for remote_mourn. */
3036 remote_mourn_1 (target)
3037 struct target_ops *target;
3039 unpush_target (target);
3040 generic_mourn_inferior ();
3043 /* In the extended protocol we want to be able to do things like
3044 "run" and have them basically work as expected. So we need
3045 a special create_inferior function.
3047 FIXME: One day add support for changing the exec file
3048 we're debugging, arguments and an environment. */
3051 extended_remote_create_inferior (exec_file, args, env)
3056 /* Rip out the breakpoints; we'll reinsert them after restarting
3057 the remote server. */
3058 remove_breakpoints ();
3060 /* Now restart the remote server. */
3061 extended_remote_restart ();
3063 /* Now put the breakpoints back in. This way we're safe if the
3064 restart function works via a unix fork on the remote side. */
3065 insert_breakpoints ();
3067 /* Clean up from the last time we were running. */
3068 clear_proceed_status ();
3070 /* Let the remote process run. */
3071 proceed (-1, TARGET_SIGNAL_0, 0);
3075 /* On some machines, e.g. 68k, we may use a different breakpoint instruction
3076 than other targets; in those use REMOTE_BREAKPOINT instead of just
3077 BREAKPOINT. Also, bi-endian targets may define LITTLE_REMOTE_BREAKPOINT
3078 and BIG_REMOTE_BREAKPOINT. If none of these are defined, we just call
3079 the standard routines that are in mem-break.c. */
3081 /* FIXME, these ought to be done in a more dynamic fashion. For instance,
3082 the choice of breakpoint instruction affects target program design and
3083 vice versa, and by making it user-tweakable, the special code here
3084 goes away and we need fewer special GDB configurations. */
3086 #if defined (LITTLE_REMOTE_BREAKPOINT) && defined (BIG_REMOTE_BREAKPOINT) && !defined(REMOTE_BREAKPOINT)
3087 #define REMOTE_BREAKPOINT
3090 #ifdef REMOTE_BREAKPOINT
3092 /* If the target isn't bi-endian, just pretend it is. */
3093 #if !defined (LITTLE_REMOTE_BREAKPOINT) && !defined (BIG_REMOTE_BREAKPOINT)
3094 #define LITTLE_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
3095 #define BIG_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
3098 static unsigned char big_break_insn[] = BIG_REMOTE_BREAKPOINT;
3099 static unsigned char little_break_insn[] = LITTLE_REMOTE_BREAKPOINT;
3101 #endif /* REMOTE_BREAKPOINT */
3103 /* Insert a breakpoint on targets that don't have any better breakpoint
3104 support. We read the contents of the target location and stash it,
3105 then overwrite it with a breakpoint instruction. ADDR is the target
3106 location in the target machine. CONTENTS_CACHE is a pointer to
3107 memory allocated for saving the target contents. It is guaranteed
3108 by the caller to be long enough to save sizeof BREAKPOINT bytes (this
3109 is accomplished via BREAKPOINT_MAX). */
3112 remote_insert_breakpoint (addr, contents_cache)
3114 char *contents_cache;
3116 #ifdef REMOTE_BREAKPOINT
3119 val = target_read_memory (addr, contents_cache, sizeof big_break_insn);
3123 if (TARGET_BYTE_ORDER == BIG_ENDIAN)
3124 val = target_write_memory (addr, (char *) big_break_insn,
3125 sizeof big_break_insn);
3127 val = target_write_memory (addr, (char *) little_break_insn,
3128 sizeof little_break_insn);
3133 return memory_insert_breakpoint (addr, contents_cache);
3134 #endif /* REMOTE_BREAKPOINT */
3138 remote_remove_breakpoint (addr, contents_cache)
3140 char *contents_cache;
3142 #ifdef REMOTE_BREAKPOINT
3143 return target_write_memory (addr, contents_cache, sizeof big_break_insn);
3145 return memory_remove_breakpoint (addr, contents_cache);
3146 #endif /* REMOTE_BREAKPOINT */
3149 /* Some targets are only capable of doing downloads, and afterwards
3150 they switch to the remote serial protocol. This function provides
3151 a clean way to get from the download target to the remote target.
3152 It's basically just a wrapper so that we don't have to expose any
3153 of the internal workings of remote.c.
3155 Prior to calling this routine, you should shutdown the current
3156 target code, else you will get the "A program is being debugged
3157 already..." message. Usually a call to pop_target() suffices. */
3160 push_remote_target (name, from_tty)
3164 printf_filtered ("Switching to remote protocol\n");
3165 remote_open (name, from_tty);
3168 /* Other targets want to use the entire remote serial module but with
3169 certain remote_ops overridden. */
3172 open_remote_target (name, from_tty, target, extended_p)
3175 struct target_ops *target;
3178 printf_filtered ("Selecting the %sremote protocol\n",
3179 (extended_p ? "extended-" : ""));
3180 remote_open_1 (name, from_tty, target, extended_p);
3183 /* Table used by the crc32 function to calcuate the checksum. */
3185 static unsigned long crc32_table[256] = {0, 0};
3187 static unsigned long
3188 crc32 (buf, len, crc)
3193 if (! crc32_table[1])
3195 /* Initialize the CRC table and the decoding table. */
3199 for (i = 0; i < 256; i++)
3201 for (c = i << 24, j = 8; j > 0; --j)
3202 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
3209 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
3215 /* compare-sections command
3217 With no arguments, compares each loadable section in the exec bfd
3218 with the same memory range on the target, and reports mismatches.
3219 Useful for verifying the image on the target against the exec file.
3220 Depends on the target understanding the new "qCRC:" request. */
3223 compare_sections_command (args, from_tty)
3228 unsigned long host_crc, target_crc;
3229 extern bfd *exec_bfd;
3230 struct cleanup *old_chain;
3231 char *tmp, *sectdata, *sectname, buf[PBUFSIZ];
3238 error ("command cannot be used without an exec file");
3239 if (!current_target.to_shortname ||
3240 strcmp (current_target.to_shortname, "remote") != 0)
3241 error ("command can only be used with remote target");
3243 for (s = exec_bfd->sections; s; s = s->next)
3245 if (!(s->flags & SEC_LOAD))
3246 continue; /* skip non-loadable section */
3248 size = bfd_get_section_size_before_reloc (s);
3250 continue; /* skip zero-length section */
3252 sectname = (char *) bfd_get_section_name (exec_bfd, s);
3253 if (args && strcmp (args, sectname) != 0)
3254 continue; /* not the section selected by user */
3256 matched = 1; /* do this section */
3258 /* FIXME: assumes lma can fit into long */
3259 sprintf (buf, "qCRC:%lx,%lx", (long) lma, (long) size);
3262 /* be clever; compute the host_crc before waiting for target reply */
3263 sectdata = xmalloc (size);
3264 old_chain = make_cleanup (free, sectdata);
3265 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
3266 host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
3270 error ("target memory fault, section %s, range 0x%08x -- 0x%08x",
3271 sectname, lma, lma + size);
3273 error ("remote target does not support this operation");
3275 for (target_crc = 0, tmp = &buf[1]; *tmp; tmp++)
3276 target_crc = target_crc * 16 + fromhex (*tmp);
3278 printf_filtered ("Section %s, range 0x%08x -- 0x%08x: ",
3279 sectname, lma, lma + size);
3280 if (host_crc == target_crc)
3281 printf_filtered ("matched.\n");
3284 printf_filtered ("MIS-MATCHED!\n");
3288 do_cleanups (old_chain);
3291 warning ("One or more sections of the remote executable does not match\n\
3292 the loaded file\n");
3293 if (args && !matched)
3294 printf_filtered ("No loaded section named '%s'.\n", args);
3298 remote_query (query_type, buf, outbuf, bufsiz)
3306 char *p2 = &buf2[0];
3310 error ("null pointer to remote bufer size specified");
3312 /* minimum outbuf size is PBUFSIZE - if bufsiz is not large enough let
3313 the caller know and return what the minimum size is */
3314 /* Note: a zero bufsiz can be used to query the minimum buffer size */
3315 if ( *bufsiz < PBUFSIZ )
3321 /* except for querying the minimum buffer size, target must be open */
3323 error ("remote query is only available after target open");
3325 /* we only take uppercase letters as query types, at least for now */
3326 if ( (query_type < 'A') || (query_type > 'Z') )
3327 error ("invalid remote query type");
3330 error ("null remote query specified");
3333 error ("remote query requires a buffer to receive data");
3340 /* we used one buffer char for the remote protocol q command and another
3341 for the query type. As the remote protocol encapsulation uses 4 chars
3342 plus one extra in case we are debugging (remote_debug),
3343 we have PBUFZIZ - 7 left to pack the query string */
3345 while ( buf[i] && (i < (PBUFSIZ - 8)) )
3347 /* bad caller may have sent forbidden characters */
3348 if ( (!isprint(buf[i])) || (buf[i] == '$') || (buf[i] == '#') )
3349 error ("illegal characters in query string");
3357 error ("query larger than available buffer");
3360 if ( i < 0 ) return i;
3368 packet_command (args, from_tty)
3375 error ("command can only be used with remote target");
3378 error ("remote-packet command requires packet text as argument");
3380 puts_filtered ("sending: ");
3381 print_packet (args);
3382 puts_filtered ("\n");
3386 puts_filtered ("received: ");
3388 puts_filtered ("\n");
3392 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------------- */
3394 static void display_thread_info PARAMS ((struct gdb_ext_thread_info *info));
3396 static void threadset_test_cmd PARAMS ((char *cmd, int tty));
3398 static void threadalive_test PARAMS ((char *cmd, int tty));
3400 static void threadlist_test_cmd PARAMS ((char *cmd, int tty));
3402 int get_and_display_threadinfo PARAMS ((threadref *ref));
3404 static void threadinfo_test_cmd PARAMS ((char *cmd, int tty));
3406 static int thread_display_step PARAMS ((threadref *ref, void *context));
3408 static void threadlist_update_test_cmd PARAMS ((char *cmd, int tty));
3410 static void init_remote_threadtests PARAMS ((void));
3412 #define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid */
3415 threadset_test_cmd (cmd, tty)
3419 int sample_thread = SAMPLE_THREAD;
3421 printf_filtered ("Remote threadset test\n");
3422 set_thread (sample_thread, 1);
3427 threadalive_test (cmd, tty)
3431 int sample_thread = SAMPLE_THREAD;
3433 if (remote_thread_alive (sample_thread))
3434 printf_filtered ("PASS: Thread alive test\n");
3436 printf_filtered ("FAIL: Thread alive test\n");
3439 void output_threadid PARAMS ((char *title, threadref * ref));
3442 output_threadid (title, ref)
3448 pack_threadid (&hexid[0], ref); /* Convert threead id into hex */
3450 printf_filtered ("%s %s\n", title, (&hexid[0]));
3454 threadlist_test_cmd (cmd, tty)
3459 threadref nextthread;
3460 int done, result_count;
3461 threadref threadlist[3];
3463 printf_filtered ("Remote Threadlist test\n");
3464 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
3465 &result_count, &threadlist[0]))
3466 printf_filtered ("FAIL: threadlist test\n");
3469 threadref *scan = threadlist;
3470 threadref *limit = scan + result_count;
3472 while (scan < limit)
3473 output_threadid (" thread ", scan++);
3478 display_thread_info (info)
3479 struct gdb_ext_thread_info *info;
3481 output_threadid ("Threadid: ", &info->threadid);
3482 printf_filtered ("Name: %s\n ", info->shortname);
3483 printf_filtered ("State: %s\n", info->display);
3484 printf_filtered ("other: %s\n\n", info->more_display);
3488 get_and_display_threadinfo (ref)
3493 struct gdb_ext_thread_info threadinfo;
3495 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3496 | TAG_MOREDISPLAY | TAG_DISPLAY;
3497 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
3498 display_thread_info (&threadinfo);
3503 threadinfo_test_cmd (cmd, tty)
3507 int athread = SAMPLE_THREAD;
3511 int_to_threadref (&thread, athread);
3512 printf_filtered ("Remote Threadinfo test\n");
3513 if (!get_and_display_threadinfo (&thread))
3514 printf_filtered ("FAIL cannot get thread info\n");
3518 thread_display_step (ref, context)
3522 /* output_threadid(" threadstep ",ref); *//* simple test */
3523 return get_and_display_threadinfo (ref);
3527 threadlist_update_test_cmd (cmd, tty)
3531 printf_filtered ("Remote Threadlist update test\n");
3532 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
3536 init_remote_threadtests (void)
3538 add_com ("tlist", class_obscure, threadlist_test_cmd,
3539 "Fetch and print the remote list of thread identifiers, one pkt only");
3540 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
3541 "Fetch and display info about one thread");
3542 add_com ("tset", class_obscure, threadset_test_cmd,
3543 "Test setting to a different thread");
3544 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
3545 "Iterate through updating all remote thread info");
3546 add_com ("talive", class_obscure, threadalive_test,
3547 " Remote thread alive test ");
3555 remote_ops.to_shortname = "remote";
3556 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
3558 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
3559 Specify the serial device it is connected to (e.g. /dev/ttya).";
3560 remote_ops.to_open = remote_open;
3561 remote_ops.to_close = remote_close;
3562 remote_ops.to_detach = remote_detach;
3563 remote_ops.to_resume = remote_resume;
3564 remote_ops.to_wait = remote_wait;
3565 remote_ops.to_fetch_registers = remote_fetch_registers;
3566 remote_ops.to_store_registers = remote_store_registers;
3567 remote_ops.to_prepare_to_store = remote_prepare_to_store;
3568 remote_ops.to_xfer_memory = remote_xfer_memory;
3569 remote_ops.to_files_info = remote_files_info;
3570 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
3571 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
3572 remote_ops.to_kill = remote_kill;
3573 remote_ops.to_load = generic_load;
3574 remote_ops.to_mourn_inferior = remote_mourn;
3575 remote_ops.to_thread_alive = remote_thread_alive;
3576 remote_ops.to_stop = remote_stop;
3577 remote_ops.to_query = remote_query;
3578 remote_ops.to_stratum = process_stratum;
3579 remote_ops.to_has_all_memory = 1;
3580 remote_ops.to_has_memory = 1;
3581 remote_ops.to_has_stack = 1;
3582 remote_ops.to_has_registers = 1;
3583 remote_ops.to_has_execution = 1;
3584 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
3585 remote_ops.to_magic = OPS_MAGIC;
3588 /* Set up the extended remote vector by making a copy of the standard
3589 remote vector and adding to it. */
3592 init_extended_remote_ops ()
3594 extended_remote_ops = remote_ops;
3596 extended_remote_ops.to_shortname = "extended-remote";
3597 extended_remote_ops.to_longname =
3598 "Extended remote serial target in gdb-specific protocol";
3599 extended_remote_ops.to_doc =
3600 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
3601 Specify the serial device it is connected to (e.g. /dev/ttya).",
3602 extended_remote_ops.to_open = extended_remote_open;
3603 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
3604 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
3608 _initialize_remote ()
3611 add_target (&remote_ops);
3613 init_extended_remote_ops ();
3614 add_target (&extended_remote_ops);
3615 init_remote_threads ();
3617 init_remote_threadtests ();
3620 add_cmd ("compare-sections", class_obscure, compare_sections_command,
3621 "Compare section data on target to the exec file.\n\
3622 Argument is a single section name (default: all loaded sections).",
3625 add_cmd ("packet", class_maintenance, packet_command,
3626 "Send an arbitrary packet to a remote target.\n\
3627 maintenance packet TEXT\n\
3628 If GDB is talking to an inferior via the GDB serial protocol, then\n\
3629 this command sends the string TEXT to the inferior, and displays the\n\
3630 response packet. GDB supplies the initial `$' character, and the\n\
3631 terminating `#' character and checksum.",
3636 (add_set_cmd ("remotechat", no_class,
3637 var_zinteger, (char *)&remote_chat,
3638 "Set remote port interacts with target.\n",
3641 #endif /* REMOTE_CHAT */
3644 (add_set_cmd ("remotetimeout", no_class,
3645 var_integer, (char *)&remote_timeout,
3646 "Set timeout value for remote read.\n",
3651 (add_set_cmd ("remotebreak", no_class,
3652 var_integer, (char *)&remote_break,
3653 "Set whether to send break if interrupted.\n",
3658 (add_set_cmd ("remotewritesize", no_class,
3659 var_integer, (char *)&remote_write_size,
3660 "Set the maximum number of bytes per memory write packet.\n",
3664 remote_address_size = TARGET_PTR_BIT;
3666 (add_set_cmd ("remoteaddresssize", class_obscure,
3667 var_integer, (char *)&remote_address_size,
3668 "Set the maximum size of the address (in bits) \
3669 in a memory packet.\n",
3673 add_show_from_set (add_set_cmd ("remotebinarydownload", no_class,
3674 var_boolean, (char *) &remote_binary_download,
3675 "Set binary downloads.\n", &setlist),