1 /* Remote utility routines for the remote server for GDB.
2 Copyright (C) 1986, 1989, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3 2001, 2002, 2003, 2004, 2005, 2006, 2007 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., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA. */
27 #include <sys/ioctl.h>
31 #include <netinet/in.h>
34 #include <sys/socket.h>
39 #if HAVE_NETINET_TCP_H
40 #include <netinet/tcp.h>
43 #include <sys/ioctl.h>
50 #include <arpa/inet.h>
59 #ifndef HAVE_SOCKLEN_T
60 typedef int socklen_t;
63 /* A cache entry for a successfully looked-up symbol. */
68 struct sym_cache *next;
71 /* The symbol cache. */
72 static struct sym_cache *symbol_cache;
74 /* If this flag has been set, assume cache misses are
76 int all_symbols_looked_up;
79 struct ui_file *gdb_stdlog;
81 static int remote_desc;
83 /* FIXME headerize? */
84 extern int using_threads;
85 extern int debug_threads;
88 # define read(fd, buf, len) recv (fd, buf, len, 0)
89 # define write(fd, buf, len) send (fd, buf, len, 0)
92 /* Open a connection to a remote debugger.
93 NAME is the filename used for communication. */
96 remote_open (char *name)
98 #if defined(F_SETFL) && defined (FASYNC)
103 port_str = strchr (name, ':');
104 if (port_str == NULL)
107 error ("Only <host>:<port> is supported on this platform.");
111 if (stat (name, &statbuf) == 0
112 && (S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode)))
113 remote_desc = open (name, O_RDWR);
121 perror_with_name ("Could not open remote device");
125 struct termios termios;
126 tcgetattr (remote_desc, &termios);
131 termios.c_cflag &= ~(CSIZE | PARENB);
132 termios.c_cflag |= CLOCAL | CS8;
133 termios.c_cc[VMIN] = 1;
134 termios.c_cc[VTIME] = 0;
136 tcsetattr (remote_desc, TCSANOW, &termios);
142 struct termio termio;
143 ioctl (remote_desc, TCGETA, &termio);
148 termio.c_cflag &= ~(CSIZE | PARENB);
149 termio.c_cflag |= CLOCAL | CS8;
150 termio.c_cc[VMIN] = 1;
151 termio.c_cc[VTIME] = 0;
153 ioctl (remote_desc, TCSETA, &termio);
161 ioctl (remote_desc, TIOCGETP, &sg);
163 ioctl (remote_desc, TIOCSETP, &sg);
167 fprintf (stderr, "Remote debugging using %s\n", name);
168 #endif /* USE_WIN32API */
173 static int winsock_initialized;
177 struct sockaddr_in sockaddr;
181 port_str = strchr (name, ':');
183 port = atoi (port_str + 1);
186 if (!winsock_initialized)
190 WSAStartup (MAKEWORD (1, 0), &wsad);
191 winsock_initialized = 1;
195 tmp_desc = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
197 perror_with_name ("Can't open socket");
199 /* Allow rapid reuse of this port. */
201 setsockopt (tmp_desc, SOL_SOCKET, SO_REUSEADDR, (char *) &tmp,
204 sockaddr.sin_family = PF_INET;
205 sockaddr.sin_port = htons (port);
206 sockaddr.sin_addr.s_addr = INADDR_ANY;
208 if (bind (tmp_desc, (struct sockaddr *) &sockaddr, sizeof (sockaddr))
209 || listen (tmp_desc, 1))
210 perror_with_name ("Can't bind address");
212 fprintf (stderr, "Listening on port %d\n", port);
215 tmp = sizeof (sockaddr);
216 remote_desc = accept (tmp_desc, (struct sockaddr *) &sockaddr, &tmp);
217 if (remote_desc == -1)
218 perror_with_name ("Accept failed");
220 /* Enable TCP keep alive process. */
222 setsockopt (tmp_desc, SOL_SOCKET, SO_KEEPALIVE, (char *) &tmp, sizeof (tmp));
224 /* Tell TCP not to delay small packets. This greatly speeds up
225 interactive response. */
227 setsockopt (remote_desc, IPPROTO_TCP, TCP_NODELAY,
228 (char *) &tmp, sizeof (tmp));
232 close (tmp_desc); /* No longer need this */
234 signal (SIGPIPE, SIG_IGN); /* If we don't do this, then gdbserver simply
235 exits when the remote side dies. */
237 closesocket (tmp_desc); /* No longer need this */
240 /* Convert IP address to string. */
241 fprintf (stderr, "Remote debugging from host %s\n",
242 inet_ntoa (sockaddr.sin_addr));
245 #if defined(F_SETFL) && defined (FASYNC)
246 save_fcntl_flags = fcntl (remote_desc, F_GETFL, 0);
247 fcntl (remote_desc, F_SETFL, save_fcntl_flags | FASYNC);
248 #if defined (F_SETOWN)
249 fcntl (remote_desc, F_SETOWN, getpid ());
259 closesocket (remote_desc);
265 /* Convert hex digit A to a number. */
270 if (a >= '0' && a <= '9')
272 else if (a >= 'a' && a <= 'f')
275 error ("Reply contains invalid hex digit");
280 unhexify (char *bin, const char *hex, int count)
284 for (i = 0; i < count; i++)
286 if (hex[0] == 0 || hex[1] == 0)
288 /* Hex string is short, or of uneven length.
289 Return the count that has been converted so far. */
292 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
299 decode_address (CORE_ADDR *addrp, const char *start, int len)
306 for (i = 0; i < len; i++)
310 addr = addr | (fromhex (ch) & 0x0f);
316 decode_address_to_semicolon (CORE_ADDR *addrp, const char *start)
321 while (*end != '\0' && *end != ';')
324 decode_address (addrp, start, end - start);
331 /* Convert number NIB to a hex digit. */
339 return 'a' + nib - 10;
343 hexify (char *hex, const char *bin, int count)
347 /* May use a length, or a nul-terminated string as input. */
349 count = strlen (bin);
351 for (i = 0; i < count; i++)
353 *hex++ = tohex ((*bin >> 4) & 0xf);
354 *hex++ = tohex (*bin++ & 0xf);
360 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
361 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
362 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
363 (which may be more than *OUT_LEN due to escape characters). The
364 total number of bytes in the output buffer will be at most
368 remote_escape_output (const gdb_byte *buffer, int len,
369 gdb_byte *out_buf, int *out_len,
372 int input_index, output_index;
375 for (input_index = 0; input_index < len; input_index++)
377 gdb_byte b = buffer[input_index];
379 if (b == '$' || b == '#' || b == '}' || b == '*')
381 /* These must be escaped. */
382 if (output_index + 2 > out_maxlen)
384 out_buf[output_index++] = '}';
385 out_buf[output_index++] = b ^ 0x20;
389 if (output_index + 1 > out_maxlen)
391 out_buf[output_index++] = b;
395 *out_len = input_index;
399 /* Convert BUFFER, escaped data LEN bytes long, into binary data
400 in OUT_BUF. Return the number of bytes written to OUT_BUF.
401 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
403 This function reverses remote_escape_output. It allows more
404 escaped characters than that function does, in particular because
405 '*' must be escaped to avoid the run-length encoding processing
406 in reading packets. */
409 remote_unescape_input (const gdb_byte *buffer, int len,
410 gdb_byte *out_buf, int out_maxlen)
412 int input_index, output_index;
417 for (input_index = 0; input_index < len; input_index++)
419 gdb_byte b = buffer[input_index];
421 if (output_index + 1 > out_maxlen)
422 error ("Received too much data from the target.");
426 out_buf[output_index++] = b ^ 0x20;
432 out_buf[output_index++] = b;
436 error ("Unmatched escape character in target response.");
441 /* Look for a sequence of characters which can be run-length encoded.
442 If there are any, update *CSUM and *P. Otherwise, output the
443 single character. Return the number of characters consumed. */
446 try_rle (char *buf, int remaining, unsigned char *csum, char **p)
450 /* Always output the character. */
454 /* Don't go past '~'. */
458 for (n = 1; n < remaining; n++)
459 if (buf[n] != buf[0])
462 /* N is the index of the first character not the same as buf[0].
463 buf[0] is counted twice, so by decrementing N, we get the number
464 of characters the RLE sequence will replace. */
470 /* Skip the frame characters. The manual says to skip '+' and '-'
471 also, but there's no reason to. Unfortunately these two unusable
472 characters double the encoded length of a four byte zero
474 while (n + 29 == '$' || n + 29 == '#')
485 /* Send a packet to the remote machine, with error checking.
486 The data of the packet is in BUF, and the length of the
487 packet is in CNT. Returns >= 0 on success, -1 otherwise. */
490 putpkt_binary (char *buf, int cnt)
493 unsigned char csum = 0;
498 buf2 = malloc (PBUFSIZ);
500 /* Copy the packet into buffer BUF2, encapsulating it
501 and giving it a checksum. */
506 for (i = 0; i < cnt;)
507 i += try_rle (buf + i, cnt - i, &csum, &p);
510 *p++ = tohex ((csum >> 4) & 0xf);
511 *p++ = tohex (csum & 0xf);
515 /* Send it over and over until we get a positive ack. */
521 if (write (remote_desc, buf2, p - buf2) != p - buf2)
523 perror ("putpkt(write)");
529 fprintf (stderr, "putpkt (\"%s\"); [looking for ack]\n", buf2);
532 cc = read (remote_desc, buf3, 1);
535 fprintf (stderr, "[received '%c' (0x%x)]\n", buf3[0], buf3[0]);
542 fprintf (stderr, "putpkt(read): Got EOF\n");
544 perror ("putpkt(read)");
550 /* Check for an input interrupt while we're here. */
551 if (buf3[0] == '\003')
552 (*the_target->send_signal) (SIGINT);
554 while (buf3[0] != '+');
557 return 1; /* Success! */
560 /* Send a packet to the remote machine, with error checking. The data
561 of the packet is in BUF, and the packet should be a NUL-terminated
562 string. Returns >= 0 on success, -1 otherwise. */
567 return putpkt_binary (buf, strlen (buf));
572 /* Come here when we get an input interrupt from the remote side. This
573 interrupt should only be active while we are waiting for the child to do
574 something. About the only thing that should come through is a ^C, which
575 will cause us to send a SIGINT to the child. */
578 input_interrupt (int unused)
581 struct timeval immediate = { 0, 0 };
583 /* Protect against spurious interrupts. This has been observed to
584 be a problem under NetBSD 1.4 and 1.5. */
587 FD_SET (remote_desc, &readset);
588 if (select (remote_desc + 1, &readset, 0, 0, &immediate) > 0)
593 cc = read (remote_desc, &c, 1);
595 if (cc != 1 || c != '\003')
597 fprintf (stderr, "input_interrupt, count = %d c = %d ('%c')\n",
602 (*the_target->send_signal) (SIGINT);
607 /* Asynchronous I/O support. SIGIO must be enabled when waiting, in order to
608 accept Control-C from the client, and must be disabled when talking to
612 block_async_io (void)
616 sigemptyset (&sigio_set);
617 sigaddset (&sigio_set, SIGIO);
618 sigprocmask (SIG_BLOCK, &sigio_set, NULL);
623 unblock_async_io (void)
627 sigemptyset (&sigio_set);
628 sigaddset (&sigio_set, SIGIO);
629 sigprocmask (SIG_UNBLOCK, &sigio_set, NULL);
633 /* Current state of asynchronous I/O. */
634 static int async_io_enabled;
636 /* Enable asynchronous I/O. */
638 enable_async_io (void)
640 if (async_io_enabled)
644 signal (SIGIO, input_interrupt);
646 async_io_enabled = 1;
649 /* Disable asynchronous I/O. */
651 disable_async_io (void)
653 if (!async_io_enabled)
657 signal (SIGIO, SIG_IGN);
659 async_io_enabled = 0;
662 /* Returns next char from remote GDB. -1 if error. */
667 static unsigned char buf[BUFSIZ];
668 static int bufcnt = 0;
669 static unsigned char *bufp;
674 bufcnt = read (remote_desc, buf, sizeof (buf));
679 fprintf (stderr, "readchar: Got EOF\n");
688 return *bufp++ & 0x7f;
691 /* Read a packet from the remote machine, with error checking,
692 and store it in BUF. Returns length of packet, or negative if error. */
698 unsigned char csum, c1, c2;
712 fprintf (stderr, "[getpkt: discarding char '%c']\n", c);
733 c1 = fromhex (readchar ());
734 c2 = fromhex (readchar ());
736 if (csum == (c1 << 4) + c2)
739 fprintf (stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
740 (c1 << 4) + c2, csum, buf);
741 write (remote_desc, "-", 1);
746 fprintf (stderr, "getpkt (\"%s\"); [sending ack] \n", buf);
750 write (remote_desc, "+", 1);
754 fprintf (stderr, "[sent ack]\n");
770 write_enn (char *buf)
772 /* Some day, we should define the meanings of the error codes... */
780 convert_int_to_ascii (unsigned char *from, char *to, int n)
787 nib = ((ch & 0xf0) >> 4) & 0x0f;
797 convert_ascii_to_int (char *from, unsigned char *to, int n)
802 nib1 = fromhex (*from++);
803 nib2 = fromhex (*from++);
804 *to++ = (((nib1 & 0x0f) << 4) & 0xf0) | (nib2 & 0x0f);
809 outreg (int regno, char *buf)
811 if ((regno >> 12) != 0)
812 *buf++ = tohex ((regno >> 12) & 0xf);
813 if ((regno >> 8) != 0)
814 *buf++ = tohex ((regno >> 8) & 0xf);
815 *buf++ = tohex ((regno >> 4) & 0xf);
816 *buf++ = tohex (regno & 0xf);
818 collect_register_as_string (regno, buf);
819 buf += 2 * register_size (regno);
826 new_thread_notify (int id)
830 /* The `n' response is not yet part of the remote protocol. Do nothing. */
834 if (server_waiting == 0)
837 sprintf (own_buf, "n%x", id);
844 dead_thread_notify (int id)
848 /* The `x' response is not yet part of the remote protocol. Do nothing. */
852 sprintf (own_buf, "x%x", id);
859 prepare_resume_reply (char *buf, char status, unsigned char sig)
865 nib = ((sig & 0xf0) >> 4);
866 *buf++ = tohex (nib);
868 *buf++ = tohex (nib);
872 const char **regp = gdbserver_expedite_regs;
874 if (the_target->stopped_by_watchpoint != NULL
875 && (*the_target->stopped_by_watchpoint) ())
880 strncpy (buf, "watch:", 6);
883 addr = (*the_target->stopped_data_address) ();
885 /* Convert each byte of the address into two hexadecimal chars.
886 Note that we take sizeof (void *) instead of sizeof (addr);
887 this is to avoid sending a 64-bit address to a 32-bit GDB. */
888 for (i = sizeof (void *) * 2; i > 0; i--)
890 *buf++ = tohex ((addr >> (i - 1) * 4) & 0xf);
897 buf = outreg (find_regno (*regp), buf);
901 /* Formerly, if the debugger had not used any thread features we would not
902 burden it with a thread status response. This was for the benefit of
903 GDB 4.13 and older. However, in recent GDB versions the check
904 (``if (cont_thread != 0)'') does not have the desired effect because of
905 sillyness in the way that the remote protocol handles specifying a thread.
906 Since thread support relies on qSymbol support anyway, assume GDB can handle
911 unsigned int gdb_id_from_wait;
913 /* FIXME right place to set this? */
914 thread_from_wait = ((struct inferior_list_entry *)current_inferior)->id;
915 gdb_id_from_wait = thread_to_gdb_id (current_inferior);
918 fprintf (stderr, "Writing resume reply for %ld\n\n", thread_from_wait);
919 /* This if (1) ought to be unnecessary. But remote_wait in GDB
920 will claim this event belongs to inferior_ptid if we do not
921 specify a thread, and there's no way for gdbserver to know
922 what inferior_ptid is. */
923 if (1 || old_thread_from_wait != thread_from_wait)
925 general_thread = thread_from_wait;
926 sprintf (buf, "thread:%x;", gdb_id_from_wait);
928 old_thread_from_wait = thread_from_wait;
932 /* For W and X, we're done. */
937 decode_m_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr)
941 *mem_addr_ptr = *len_ptr = 0;
943 while ((ch = from[i++]) != ',')
945 *mem_addr_ptr = *mem_addr_ptr << 4;
946 *mem_addr_ptr |= fromhex (ch) & 0x0f;
949 for (j = 0; j < 4; j++)
951 if ((ch = from[i++]) == 0)
953 *len_ptr = *len_ptr << 4;
954 *len_ptr |= fromhex (ch) & 0x0f;
959 decode_M_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr,
964 *mem_addr_ptr = *len_ptr = 0;
966 while ((ch = from[i++]) != ',')
968 *mem_addr_ptr = *mem_addr_ptr << 4;
969 *mem_addr_ptr |= fromhex (ch) & 0x0f;
972 while ((ch = from[i++]) != ':')
974 *len_ptr = *len_ptr << 4;
975 *len_ptr |= fromhex (ch) & 0x0f;
978 convert_ascii_to_int (&from[i++], to, *len_ptr);
982 decode_X_packet (char *from, int packet_len, CORE_ADDR *mem_addr_ptr,
983 unsigned int *len_ptr, unsigned char *to)
987 *mem_addr_ptr = *len_ptr = 0;
989 while ((ch = from[i++]) != ',')
991 *mem_addr_ptr = *mem_addr_ptr << 4;
992 *mem_addr_ptr |= fromhex (ch) & 0x0f;
995 while ((ch = from[i++]) != ':')
997 *len_ptr = *len_ptr << 4;
998 *len_ptr |= fromhex (ch) & 0x0f;
1001 if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len - i,
1002 to, *len_ptr) != *len_ptr)
1008 /* Ask GDB for the address of NAME, and return it in ADDRP if found.
1009 Returns 1 if the symbol is found, 0 if it is not, -1 on error. */
1012 look_up_one_symbol (const char *name, CORE_ADDR *addrp)
1014 char own_buf[266], *p, *q;
1016 struct sym_cache *sym;
1018 /* Check the cache first. */
1019 for (sym = symbol_cache; sym; sym = sym->next)
1020 if (strcmp (name, sym->name) == 0)
1026 /* If we've passed the call to thread_db_look_up_symbols, then
1027 anything not in the cache must not exist; we're not interested
1028 in any libraries loaded after that point, only in symbols in
1029 libpthread.so. It might not be an appropriate time to look
1030 up a symbol, e.g. while we're trying to fetch registers. */
1031 if (all_symbols_looked_up)
1034 /* Send the request. */
1035 strcpy (own_buf, "qSymbol:");
1036 hexify (own_buf + strlen ("qSymbol:"), name, strlen (name));
1037 if (putpkt (own_buf) < 0)
1040 /* FIXME: Eventually add buffer overflow checking (to getpkt?) */
1041 len = getpkt (own_buf);
1045 if (strncmp (own_buf, "qSymbol:", strlen ("qSymbol:")) != 0)
1047 /* Malformed response. */
1050 fprintf (stderr, "Malformed response to qSymbol, ignoring.\n");
1057 p = own_buf + strlen ("qSymbol:");
1059 while (*q && *q != ':')
1062 /* Make sure we found a value for the symbol. */
1063 if (p == q || *q == '\0')
1066 decode_address (addrp, p, q - p);
1068 /* Save the symbol in our cache. */
1069 sym = malloc (sizeof (*sym));
1070 sym->name = strdup (name);
1072 sym->next = symbol_cache;