2013-03-12 Sebastian Huber <sebastian.huber@embedded-brains.de>
[binutils-gdb.git] / gdb / gdbserver / remote-utils.c
blob42c6a545c564ffcfd4054346f5c1f9e0bf5081cc
1 /* Remote utility routines for the remote server for GDB.
2 Copyright (C) 1986-2013 Free Software Foundation, Inc.
4 This file is part of GDB.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19 #include "server.h"
20 #include "terminal.h"
21 #include "target.h"
22 #include "gdbthread.h"
23 #include <stdio.h>
24 #include <string.h>
25 #if HAVE_SYS_IOCTL_H
26 #include <sys/ioctl.h>
27 #endif
28 #if HAVE_SYS_FILE_H
29 #include <sys/file.h>
30 #endif
31 #if HAVE_NETINET_IN_H
32 #include <netinet/in.h>
33 #endif
34 #if HAVE_SYS_SOCKET_H
35 #include <sys/socket.h>
36 #endif
37 #if HAVE_NETDB_H
38 #include <netdb.h>
39 #endif
40 #if HAVE_NETINET_TCP_H
41 #include <netinet/tcp.h>
42 #endif
43 #if HAVE_SYS_IOCTL_H
44 #include <sys/ioctl.h>
45 #endif
46 #if HAVE_SIGNAL_H
47 #include <signal.h>
48 #endif
49 #if HAVE_FCNTL_H
50 #include <fcntl.h>
51 #endif
52 #include <sys/time.h>
53 #if HAVE_UNISTD_H
54 #include <unistd.h>
55 #endif
56 #if HAVE_ARPA_INET_H
57 #include <arpa/inet.h>
58 #endif
59 #include "gdb_stat.h"
60 #if HAVE_ERRNO_H
61 #include <errno.h>
62 #endif
64 #if USE_WIN32API
65 #include <winsock2.h>
66 #endif
68 #if __QNX__
69 #include <sys/iomgr.h>
70 #endif /* __QNX__ */
72 #ifndef HAVE_SOCKLEN_T
73 typedef int socklen_t;
74 #endif
76 #ifndef IN_PROCESS_AGENT
78 #if USE_WIN32API
79 # define INVALID_DESCRIPTOR INVALID_SOCKET
80 #else
81 # define INVALID_DESCRIPTOR -1
82 #endif
84 /* Extra value for readchar_callback. */
85 enum {
86 /* The callback is currently not scheduled. */
87 NOT_SCHEDULED = -1
90 /* Status of the readchar callback.
91 Either NOT_SCHEDULED or the callback id. */
92 static int readchar_callback = NOT_SCHEDULED;
94 static int readchar (void);
95 static void reset_readchar (void);
96 static void reschedule (void);
98 /* A cache entry for a successfully looked-up symbol. */
99 struct sym_cache
101 char *name;
102 CORE_ADDR addr;
103 struct sym_cache *next;
106 int remote_debug = 0;
107 struct ui_file *gdb_stdlog;
109 static int remote_is_stdio = 0;
111 static gdb_fildes_t remote_desc = INVALID_DESCRIPTOR;
112 static gdb_fildes_t listen_desc = INVALID_DESCRIPTOR;
114 /* FIXME headerize? */
115 extern int using_threads;
116 extern int debug_threads;
118 /* If true, then GDB has requested noack mode. */
119 int noack_mode = 0;
120 /* If true, then we tell GDB to use noack mode by default. */
121 int transport_is_reliable = 0;
123 #ifdef USE_WIN32API
124 # define read(fd, buf, len) recv (fd, (char *) buf, len, 0)
125 # define write(fd, buf, len) send (fd, (char *) buf, len, 0)
126 #endif
129 gdb_connected (void)
131 return remote_desc != INVALID_DESCRIPTOR;
134 /* Return true if the remote connection is over stdio. */
137 remote_connection_is_stdio (void)
139 return remote_is_stdio;
142 static void
143 enable_async_notification (int fd)
145 #if defined(F_SETFL) && defined (FASYNC)
146 int save_fcntl_flags;
148 save_fcntl_flags = fcntl (fd, F_GETFL, 0);
149 fcntl (fd, F_SETFL, save_fcntl_flags | FASYNC);
150 #if defined (F_SETOWN)
151 fcntl (fd, F_SETOWN, getpid ());
152 #endif
153 #endif
156 static int
157 handle_accept_event (int err, gdb_client_data client_data)
159 struct sockaddr_in sockaddr;
160 socklen_t tmp;
162 if (debug_threads)
163 fprintf (stderr, "handling possible accept event\n");
165 tmp = sizeof (sockaddr);
166 remote_desc = accept (listen_desc, (struct sockaddr *) &sockaddr, &tmp);
167 if (remote_desc == -1)
168 perror_with_name ("Accept failed");
170 /* Enable TCP keep alive process. */
171 tmp = 1;
172 setsockopt (remote_desc, SOL_SOCKET, SO_KEEPALIVE,
173 (char *) &tmp, sizeof (tmp));
175 /* Tell TCP not to delay small packets. This greatly speeds up
176 interactive response. */
177 tmp = 1;
178 setsockopt (remote_desc, IPPROTO_TCP, TCP_NODELAY,
179 (char *) &tmp, sizeof (tmp));
181 #ifndef USE_WIN32API
182 signal (SIGPIPE, SIG_IGN); /* If we don't do this, then gdbserver simply
183 exits when the remote side dies. */
184 #endif
186 if (run_once)
188 #ifndef USE_WIN32API
189 close (listen_desc); /* No longer need this */
190 #else
191 closesocket (listen_desc); /* No longer need this */
192 #endif
195 /* Even if !RUN_ONCE no longer notice new connections. Still keep the
196 descriptor open for add_file_handler to wait for a new connection. */
197 delete_file_handler (listen_desc);
199 /* Convert IP address to string. */
200 fprintf (stderr, "Remote debugging from host %s\n",
201 inet_ntoa (sockaddr.sin_addr));
203 enable_async_notification (remote_desc);
205 /* Register the event loop handler. */
206 add_file_handler (remote_desc, handle_serial_event, NULL);
208 /* We have a new GDB connection now. If we were disconnected
209 tracing, there's a window where the target could report a stop
210 event to the event loop, and since we have a connection now, we'd
211 try to send vStopped notifications to GDB. But, don't do that
212 until GDB as selected all-stop/non-stop, and has queried the
213 threads' status ('?'). */
214 target_async (0);
216 return 0;
219 /* Prepare for a later connection to a remote debugger.
220 NAME is the filename used for communication. */
222 void
223 remote_prepare (char *name)
225 char *port_str;
226 #ifdef USE_WIN32API
227 static int winsock_initialized;
228 #endif
229 int port;
230 struct sockaddr_in sockaddr;
231 socklen_t tmp;
232 char *port_end;
234 remote_is_stdio = 0;
235 if (strcmp (name, STDIO_CONNECTION_NAME) == 0)
237 /* We need to record fact that we're using stdio sooner than the
238 call to remote_open so start_inferior knows the connection is
239 via stdio. */
240 remote_is_stdio = 1;
241 transport_is_reliable = 1;
242 return;
245 port_str = strchr (name, ':');
246 if (port_str == NULL)
248 transport_is_reliable = 0;
249 return;
252 port = strtoul (port_str + 1, &port_end, 10);
253 if (port_str[1] == '\0' || *port_end != '\0')
254 fatal ("Bad port argument: %s", name);
256 #ifdef USE_WIN32API
257 if (!winsock_initialized)
259 WSADATA wsad;
261 WSAStartup (MAKEWORD (1, 0), &wsad);
262 winsock_initialized = 1;
264 #endif
266 listen_desc = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
267 if (listen_desc == -1)
268 perror_with_name ("Can't open socket");
270 /* Allow rapid reuse of this port. */
271 tmp = 1;
272 setsockopt (listen_desc, SOL_SOCKET, SO_REUSEADDR, (char *) &tmp,
273 sizeof (tmp));
275 sockaddr.sin_family = PF_INET;
276 sockaddr.sin_port = htons (port);
277 sockaddr.sin_addr.s_addr = INADDR_ANY;
279 if (bind (listen_desc, (struct sockaddr *) &sockaddr, sizeof (sockaddr))
280 || listen (listen_desc, 1))
281 perror_with_name ("Can't bind address");
283 transport_is_reliable = 1;
286 /* Open a connection to a remote debugger.
287 NAME is the filename used for communication. */
289 void
290 remote_open (char *name)
292 char *port_str;
294 port_str = strchr (name, ':');
295 #ifdef USE_WIN32API
296 if (port_str == NULL)
297 error ("Only <host>:<port> is supported on this platform.");
298 #endif
300 if (strcmp (name, STDIO_CONNECTION_NAME) == 0)
302 fprintf (stderr, "Remote debugging using stdio\n");
304 /* Use stdin as the handle of the connection.
305 We only select on reads, for example. */
306 remote_desc = fileno (stdin);
308 enable_async_notification (remote_desc);
310 /* Register the event loop handler. */
311 add_file_handler (remote_desc, handle_serial_event, NULL);
313 #ifndef USE_WIN32API
314 else if (port_str == NULL)
316 struct stat statbuf;
318 if (stat (name, &statbuf) == 0
319 && (S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode)))
320 remote_desc = open (name, O_RDWR);
321 else
323 errno = EINVAL;
324 remote_desc = -1;
327 if (remote_desc < 0)
328 perror_with_name ("Could not open remote device");
330 #ifdef HAVE_TERMIOS
332 struct termios termios;
333 tcgetattr (remote_desc, &termios);
335 termios.c_iflag = 0;
336 termios.c_oflag = 0;
337 termios.c_lflag = 0;
338 termios.c_cflag &= ~(CSIZE | PARENB);
339 termios.c_cflag |= CLOCAL | CS8;
340 termios.c_cc[VMIN] = 1;
341 termios.c_cc[VTIME] = 0;
343 tcsetattr (remote_desc, TCSANOW, &termios);
345 #endif
347 #ifdef HAVE_TERMIO
349 struct termio termio;
350 ioctl (remote_desc, TCGETA, &termio);
352 termio.c_iflag = 0;
353 termio.c_oflag = 0;
354 termio.c_lflag = 0;
355 termio.c_cflag &= ~(CSIZE | PARENB);
356 termio.c_cflag |= CLOCAL | CS8;
357 termio.c_cc[VMIN] = 1;
358 termio.c_cc[VTIME] = 0;
360 ioctl (remote_desc, TCSETA, &termio);
362 #endif
364 #ifdef HAVE_SGTTY
366 struct sgttyb sg;
368 ioctl (remote_desc, TIOCGETP, &sg);
369 sg.sg_flags = RAW;
370 ioctl (remote_desc, TIOCSETP, &sg);
372 #endif
374 fprintf (stderr, "Remote debugging using %s\n", name);
376 enable_async_notification (remote_desc);
378 /* Register the event loop handler. */
379 add_file_handler (remote_desc, handle_serial_event, NULL);
381 #endif /* USE_WIN32API */
382 else
384 int port;
385 socklen_t len;
386 struct sockaddr_in sockaddr;
388 len = sizeof (sockaddr);
389 if (getsockname (listen_desc,
390 (struct sockaddr *) &sockaddr, &len) < 0
391 || len < sizeof (sockaddr))
392 perror_with_name ("Can't determine port");
393 port = ntohs (sockaddr.sin_port);
395 fprintf (stderr, "Listening on port %d\n", port);
396 fflush (stderr);
398 /* Register the event loop handler. */
399 add_file_handler (listen_desc, handle_accept_event, NULL);
403 void
404 remote_close (void)
406 delete_file_handler (remote_desc);
408 #ifdef USE_WIN32API
409 closesocket (remote_desc);
410 #else
411 if (! remote_connection_is_stdio ())
412 close (remote_desc);
413 #endif
414 remote_desc = INVALID_DESCRIPTOR;
416 reset_readchar ();
419 /* Convert hex digit A to a number. */
421 static int
422 fromhex (int a)
424 if (a >= '0' && a <= '9')
425 return a - '0';
426 else if (a >= 'a' && a <= 'f')
427 return a - 'a' + 10;
428 else
429 error ("Reply contains invalid hex digit");
430 return 0;
433 #endif
435 static const char hexchars[] = "0123456789abcdef";
437 static int
438 ishex (int ch, int *val)
440 if ((ch >= 'a') && (ch <= 'f'))
442 *val = ch - 'a' + 10;
443 return 1;
445 if ((ch >= 'A') && (ch <= 'F'))
447 *val = ch - 'A' + 10;
448 return 1;
450 if ((ch >= '0') && (ch <= '9'))
452 *val = ch - '0';
453 return 1;
455 return 0;
458 #ifndef IN_PROCESS_AGENT
461 unhexify (char *bin, const char *hex, int count)
463 int i;
465 for (i = 0; i < count; i++)
467 if (hex[0] == 0 || hex[1] == 0)
469 /* Hex string is short, or of uneven length.
470 Return the count that has been converted so far. */
471 return i;
473 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
474 hex += 2;
476 return i;
479 void
480 decode_address (CORE_ADDR *addrp, const char *start, int len)
482 CORE_ADDR addr;
483 char ch;
484 int i;
486 addr = 0;
487 for (i = 0; i < len; i++)
489 ch = start[i];
490 addr = addr << 4;
491 addr = addr | (fromhex (ch) & 0x0f);
493 *addrp = addr;
496 const char *
497 decode_address_to_semicolon (CORE_ADDR *addrp, const char *start)
499 const char *end;
501 end = start;
502 while (*end != '\0' && *end != ';')
503 end++;
505 decode_address (addrp, start, end - start);
507 if (*end == ';')
508 end++;
509 return end;
512 #endif
514 /* Convert number NIB to a hex digit. */
516 static int
517 tohex (int nib)
519 if (nib < 10)
520 return '0' + nib;
521 else
522 return 'a' + nib - 10;
525 #ifndef IN_PROCESS_AGENT
528 hexify (char *hex, const char *bin, int count)
530 int i;
532 /* May use a length, or a nul-terminated string as input. */
533 if (count == 0)
534 count = strlen (bin);
536 for (i = 0; i < count; i++)
538 *hex++ = tohex ((*bin >> 4) & 0xf);
539 *hex++ = tohex (*bin++ & 0xf);
541 *hex = 0;
542 return i;
545 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
546 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
547 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
548 (which may be more than *OUT_LEN due to escape characters). The
549 total number of bytes in the output buffer will be at most
550 OUT_MAXLEN. */
553 remote_escape_output (const gdb_byte *buffer, int len,
554 gdb_byte *out_buf, int *out_len,
555 int out_maxlen)
557 int input_index, output_index;
559 output_index = 0;
560 for (input_index = 0; input_index < len; input_index++)
562 gdb_byte b = buffer[input_index];
564 if (b == '$' || b == '#' || b == '}' || b == '*')
566 /* These must be escaped. */
567 if (output_index + 2 > out_maxlen)
568 break;
569 out_buf[output_index++] = '}';
570 out_buf[output_index++] = b ^ 0x20;
572 else
574 if (output_index + 1 > out_maxlen)
575 break;
576 out_buf[output_index++] = b;
580 *out_len = input_index;
581 return output_index;
584 /* Convert BUFFER, escaped data LEN bytes long, into binary data
585 in OUT_BUF. Return the number of bytes written to OUT_BUF.
586 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
588 This function reverses remote_escape_output. It allows more
589 escaped characters than that function does, in particular because
590 '*' must be escaped to avoid the run-length encoding processing
591 in reading packets. */
593 static int
594 remote_unescape_input (const gdb_byte *buffer, int len,
595 gdb_byte *out_buf, int out_maxlen)
597 int input_index, output_index;
598 int escaped;
600 output_index = 0;
601 escaped = 0;
602 for (input_index = 0; input_index < len; input_index++)
604 gdb_byte b = buffer[input_index];
606 if (output_index + 1 > out_maxlen)
607 error ("Received too much data from the target.");
609 if (escaped)
611 out_buf[output_index++] = b ^ 0x20;
612 escaped = 0;
614 else if (b == '}')
615 escaped = 1;
616 else
617 out_buf[output_index++] = b;
620 if (escaped)
621 error ("Unmatched escape character in target response.");
623 return output_index;
626 /* Look for a sequence of characters which can be run-length encoded.
627 If there are any, update *CSUM and *P. Otherwise, output the
628 single character. Return the number of characters consumed. */
630 static int
631 try_rle (char *buf, int remaining, unsigned char *csum, char **p)
633 int n;
635 /* Always output the character. */
636 *csum += buf[0];
637 *(*p)++ = buf[0];
639 /* Don't go past '~'. */
640 if (remaining > 97)
641 remaining = 97;
643 for (n = 1; n < remaining; n++)
644 if (buf[n] != buf[0])
645 break;
647 /* N is the index of the first character not the same as buf[0].
648 buf[0] is counted twice, so by decrementing N, we get the number
649 of characters the RLE sequence will replace. */
650 n--;
652 if (n < 3)
653 return 1;
655 /* Skip the frame characters. The manual says to skip '+' and '-'
656 also, but there's no reason to. Unfortunately these two unusable
657 characters double the encoded length of a four byte zero
658 value. */
659 while (n + 29 == '$' || n + 29 == '#')
660 n--;
662 *csum += '*';
663 *(*p)++ = '*';
664 *csum += n + 29;
665 *(*p)++ = n + 29;
667 return n + 1;
670 #endif
672 char *
673 unpack_varlen_hex (char *buff, /* packet to parse */
674 ULONGEST *result)
676 int nibble;
677 ULONGEST retval = 0;
679 while (ishex (*buff, &nibble))
681 buff++;
682 retval = retval << 4;
683 retval |= nibble & 0x0f;
685 *result = retval;
686 return buff;
689 #ifndef IN_PROCESS_AGENT
691 /* Write a PTID to BUF. Returns BUF+CHARACTERS_WRITTEN. */
693 char *
694 write_ptid (char *buf, ptid_t ptid)
696 int pid, tid;
698 if (multi_process)
700 pid = ptid_get_pid (ptid);
701 if (pid < 0)
702 buf += sprintf (buf, "p-%x.", -pid);
703 else
704 buf += sprintf (buf, "p%x.", pid);
706 tid = ptid_get_lwp (ptid);
707 if (tid < 0)
708 buf += sprintf (buf, "-%x", -tid);
709 else
710 buf += sprintf (buf, "%x", tid);
712 return buf;
715 ULONGEST
716 hex_or_minus_one (char *buf, char **obuf)
718 ULONGEST ret;
720 if (strncmp (buf, "-1", 2) == 0)
722 ret = (ULONGEST) -1;
723 buf += 2;
725 else
726 buf = unpack_varlen_hex (buf, &ret);
728 if (obuf)
729 *obuf = buf;
731 return ret;
734 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
735 passed the last parsed char. Returns null_ptid on error. */
736 ptid_t
737 read_ptid (char *buf, char **obuf)
739 char *p = buf;
740 char *pp;
741 ULONGEST pid = 0, tid = 0;
743 if (*p == 'p')
745 /* Multi-process ptid. */
746 pp = unpack_varlen_hex (p + 1, &pid);
747 if (*pp != '.')
748 error ("invalid remote ptid: %s\n", p);
750 p = pp + 1;
752 tid = hex_or_minus_one (p, &pp);
754 if (obuf)
755 *obuf = pp;
756 return ptid_build (pid, tid, 0);
759 /* No multi-process. Just a tid. */
760 tid = hex_or_minus_one (p, &pp);
762 /* Since the stub is not sending a process id, then default to
763 what's in the current inferior. */
764 pid = ptid_get_pid (current_ptid);
766 if (obuf)
767 *obuf = pp;
768 return ptid_build (pid, tid, 0);
771 /* Write COUNT bytes in BUF to the client.
772 The result is the number of bytes written or -1 if error.
773 This may return less than COUNT. */
775 static int
776 write_prim (const void *buf, int count)
778 if (remote_connection_is_stdio ())
779 return write (fileno (stdout), buf, count);
780 else
781 return write (remote_desc, buf, count);
784 /* Read COUNT bytes from the client and store in BUF.
785 The result is the number of bytes read or -1 if error.
786 This may return less than COUNT. */
788 static int
789 read_prim (void *buf, int count)
791 if (remote_connection_is_stdio ())
792 return read (fileno (stdin), buf, count);
793 else
794 return read (remote_desc, buf, count);
797 /* Send a packet to the remote machine, with error checking.
798 The data of the packet is in BUF, and the length of the
799 packet is in CNT. Returns >= 0 on success, -1 otherwise. */
801 static int
802 putpkt_binary_1 (char *buf, int cnt, int is_notif)
804 int i;
805 unsigned char csum = 0;
806 char *buf2;
807 char *p;
808 int cc;
810 buf2 = xmalloc (strlen ("$") + cnt + strlen ("#nn") + 1);
812 /* Copy the packet into buffer BUF2, encapsulating it
813 and giving it a checksum. */
815 p = buf2;
816 if (is_notif)
817 *p++ = '%';
818 else
819 *p++ = '$';
821 for (i = 0; i < cnt;)
822 i += try_rle (buf + i, cnt - i, &csum, &p);
824 *p++ = '#';
825 *p++ = tohex ((csum >> 4) & 0xf);
826 *p++ = tohex (csum & 0xf);
828 *p = '\0';
830 /* Send it over and over until we get a positive ack. */
834 if (write_prim (buf2, p - buf2) != p - buf2)
836 perror ("putpkt(write)");
837 free (buf2);
838 return -1;
841 if (noack_mode || is_notif)
843 /* Don't expect an ack then. */
844 if (remote_debug)
846 if (is_notif)
847 fprintf (stderr, "putpkt (\"%s\"); [notif]\n", buf2);
848 else
849 fprintf (stderr, "putpkt (\"%s\"); [noack mode]\n", buf2);
850 fflush (stderr);
852 break;
855 if (remote_debug)
857 fprintf (stderr, "putpkt (\"%s\"); [looking for ack]\n", buf2);
858 fflush (stderr);
861 cc = readchar ();
863 if (cc < 0)
865 free (buf2);
866 return -1;
869 if (remote_debug)
871 fprintf (stderr, "[received '%c' (0x%x)]\n", cc, cc);
872 fflush (stderr);
875 /* Check for an input interrupt while we're here. */
876 if (cc == '\003' && current_inferior != NULL)
877 (*the_target->request_interrupt) ();
879 while (cc != '+');
881 free (buf2);
882 return 1; /* Success! */
886 putpkt_binary (char *buf, int cnt)
888 return putpkt_binary_1 (buf, cnt, 0);
891 /* Send a packet to the remote machine, with error checking. The data
892 of the packet is in BUF, and the packet should be a NUL-terminated
893 string. Returns >= 0 on success, -1 otherwise. */
896 putpkt (char *buf)
898 return putpkt_binary (buf, strlen (buf));
902 putpkt_notif (char *buf)
904 return putpkt_binary_1 (buf, strlen (buf), 1);
907 /* Come here when we get an input interrupt from the remote side. This
908 interrupt should only be active while we are waiting for the child to do
909 something. Thus this assumes readchar:bufcnt is 0.
910 About the only thing that should come through is a ^C, which
911 will cause us to request child interruption. */
913 static void
914 input_interrupt (int unused)
916 fd_set readset;
917 struct timeval immediate = { 0, 0 };
919 /* Protect against spurious interrupts. This has been observed to
920 be a problem under NetBSD 1.4 and 1.5. */
922 FD_ZERO (&readset);
923 FD_SET (remote_desc, &readset);
924 if (select (remote_desc + 1, &readset, 0, 0, &immediate) > 0)
926 int cc;
927 char c = 0;
929 cc = read_prim (&c, 1);
931 if (cc != 1 || c != '\003' || current_inferior == NULL)
933 fprintf (stderr, "input_interrupt, count = %d c = %d ('%c')\n",
934 cc, c, c);
935 return;
938 (*the_target->request_interrupt) ();
942 /* Check if the remote side sent us an interrupt request (^C). */
943 void
944 check_remote_input_interrupt_request (void)
946 /* This function may be called before establishing communications,
947 therefore we need to validate the remote descriptor. */
949 if (remote_desc == INVALID_DESCRIPTOR)
950 return;
952 input_interrupt (0);
955 /* Asynchronous I/O support. SIGIO must be enabled when waiting, in order to
956 accept Control-C from the client, and must be disabled when talking to
957 the client. */
959 static void
960 unblock_async_io (void)
962 #ifndef USE_WIN32API
963 sigset_t sigio_set;
965 sigemptyset (&sigio_set);
966 sigaddset (&sigio_set, SIGIO);
967 sigprocmask (SIG_UNBLOCK, &sigio_set, NULL);
968 #endif
971 #ifdef __QNX__
972 static void
973 nto_comctrl (int enable)
975 struct sigevent event;
977 if (enable)
979 event.sigev_notify = SIGEV_SIGNAL_THREAD;
980 event.sigev_signo = SIGIO;
981 event.sigev_code = 0;
982 event.sigev_value.sival_ptr = NULL;
983 event.sigev_priority = -1;
984 ionotify (remote_desc, _NOTIFY_ACTION_POLLARM, _NOTIFY_COND_INPUT,
985 &event);
987 else
988 ionotify (remote_desc, _NOTIFY_ACTION_POLL, _NOTIFY_COND_INPUT, NULL);
990 #endif /* __QNX__ */
993 /* Current state of asynchronous I/O. */
994 static int async_io_enabled;
996 /* Enable asynchronous I/O. */
997 void
998 enable_async_io (void)
1000 if (async_io_enabled)
1001 return;
1003 #ifndef USE_WIN32API
1004 signal (SIGIO, input_interrupt);
1005 #endif
1006 async_io_enabled = 1;
1007 #ifdef __QNX__
1008 nto_comctrl (1);
1009 #endif /* __QNX__ */
1012 /* Disable asynchronous I/O. */
1013 void
1014 disable_async_io (void)
1016 if (!async_io_enabled)
1017 return;
1019 #ifndef USE_WIN32API
1020 signal (SIGIO, SIG_IGN);
1021 #endif
1022 async_io_enabled = 0;
1023 #ifdef __QNX__
1024 nto_comctrl (0);
1025 #endif /* __QNX__ */
1029 void
1030 initialize_async_io (void)
1032 /* Make sure that async I/O starts disabled. */
1033 async_io_enabled = 1;
1034 disable_async_io ();
1036 /* Make sure the signal is unblocked. */
1037 unblock_async_io ();
1040 /* Internal buffer used by readchar.
1041 These are global to readchar because reschedule_remote needs to be
1042 able to tell whether the buffer is empty. */
1044 static unsigned char readchar_buf[BUFSIZ];
1045 static int readchar_bufcnt = 0;
1046 static unsigned char *readchar_bufp;
1048 /* Returns next char from remote GDB. -1 if error. */
1050 static int
1051 readchar (void)
1053 int ch;
1055 if (readchar_bufcnt == 0)
1057 readchar_bufcnt = read_prim (readchar_buf, sizeof (readchar_buf));
1059 if (readchar_bufcnt <= 0)
1061 if (readchar_bufcnt == 0)
1062 fprintf (stderr, "readchar: Got EOF\n");
1063 else
1064 perror ("readchar");
1066 return -1;
1069 readchar_bufp = readchar_buf;
1072 readchar_bufcnt--;
1073 ch = *readchar_bufp++;
1074 reschedule ();
1075 return ch;
1078 /* Reset the readchar state machine. */
1080 static void
1081 reset_readchar (void)
1083 readchar_bufcnt = 0;
1084 if (readchar_callback != NOT_SCHEDULED)
1086 delete_callback_event (readchar_callback);
1087 readchar_callback = NOT_SCHEDULED;
1091 /* Process remaining data in readchar_buf. */
1093 static int
1094 process_remaining (void *context)
1096 int res;
1098 /* This is a one-shot event. */
1099 readchar_callback = NOT_SCHEDULED;
1101 if (readchar_bufcnt > 0)
1102 res = handle_serial_event (0, NULL);
1103 else
1104 res = 0;
1106 return res;
1109 /* If there is still data in the buffer, queue another event to process it,
1110 we can't sleep in select yet. */
1112 static void
1113 reschedule (void)
1115 if (readchar_bufcnt > 0 && readchar_callback == NOT_SCHEDULED)
1116 readchar_callback = append_callback_event (process_remaining, NULL);
1119 /* Read a packet from the remote machine, with error checking,
1120 and store it in BUF. Returns length of packet, or negative if error. */
1123 getpkt (char *buf)
1125 char *bp;
1126 unsigned char csum, c1, c2;
1127 int c;
1129 while (1)
1131 csum = 0;
1133 while (1)
1135 c = readchar ();
1136 if (c == '$')
1137 break;
1138 if (remote_debug)
1140 fprintf (stderr, "[getpkt: discarding char '%c']\n", c);
1141 fflush (stderr);
1144 if (c < 0)
1145 return -1;
1148 bp = buf;
1149 while (1)
1151 c = readchar ();
1152 if (c < 0)
1153 return -1;
1154 if (c == '#')
1155 break;
1156 *bp++ = c;
1157 csum += c;
1159 *bp = 0;
1161 c1 = fromhex (readchar ());
1162 c2 = fromhex (readchar ());
1164 if (csum == (c1 << 4) + c2)
1165 break;
1167 if (noack_mode)
1169 fprintf (stderr,
1170 "Bad checksum, sentsum=0x%x, csum=0x%x, "
1171 "buf=%s [no-ack-mode, Bad medium?]\n",
1172 (c1 << 4) + c2, csum, buf);
1173 /* Not much we can do, GDB wasn't expecting an ack/nac. */
1174 break;
1177 fprintf (stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
1178 (c1 << 4) + c2, csum, buf);
1179 if (write_prim ("-", 1) != 1)
1180 return -1;
1183 if (!noack_mode)
1185 if (remote_debug)
1187 fprintf (stderr, "getpkt (\"%s\"); [sending ack] \n", buf);
1188 fflush (stderr);
1191 if (write_prim ("+", 1) != 1)
1192 return -1;
1194 if (remote_debug)
1196 fprintf (stderr, "[sent ack]\n");
1197 fflush (stderr);
1200 else
1202 if (remote_debug)
1204 fprintf (stderr, "getpkt (\"%s\"); [no ack sent] \n", buf);
1205 fflush (stderr);
1209 return bp - buf;
1212 void
1213 write_ok (char *buf)
1215 buf[0] = 'O';
1216 buf[1] = 'K';
1217 buf[2] = '\0';
1220 void
1221 write_enn (char *buf)
1223 /* Some day, we should define the meanings of the error codes... */
1224 buf[0] = 'E';
1225 buf[1] = '0';
1226 buf[2] = '1';
1227 buf[3] = '\0';
1230 #endif
1232 void
1233 convert_int_to_ascii (const unsigned char *from, char *to, int n)
1235 int nib;
1236 int ch;
1237 while (n--)
1239 ch = *from++;
1240 nib = ((ch & 0xf0) >> 4) & 0x0f;
1241 *to++ = tohex (nib);
1242 nib = ch & 0x0f;
1243 *to++ = tohex (nib);
1245 *to++ = 0;
1248 #ifndef IN_PROCESS_AGENT
1250 void
1251 convert_ascii_to_int (const char *from, unsigned char *to, int n)
1253 int nib1, nib2;
1254 while (n--)
1256 nib1 = fromhex (*from++);
1257 nib2 = fromhex (*from++);
1258 *to++ = (((nib1 & 0x0f) << 4) & 0xf0) | (nib2 & 0x0f);
1262 static char *
1263 outreg (struct regcache *regcache, int regno, char *buf)
1265 if ((regno >> 12) != 0)
1266 *buf++ = tohex ((regno >> 12) & 0xf);
1267 if ((regno >> 8) != 0)
1268 *buf++ = tohex ((regno >> 8) & 0xf);
1269 *buf++ = tohex ((regno >> 4) & 0xf);
1270 *buf++ = tohex (regno & 0xf);
1271 *buf++ = ':';
1272 collect_register_as_string (regcache, regno, buf);
1273 buf += 2 * register_size (regno);
1274 *buf++ = ';';
1276 return buf;
1279 void
1280 new_thread_notify (int id)
1282 char own_buf[256];
1284 /* The `n' response is not yet part of the remote protocol. Do nothing. */
1285 if (1)
1286 return;
1288 if (server_waiting == 0)
1289 return;
1291 sprintf (own_buf, "n%x", id);
1292 disable_async_io ();
1293 putpkt (own_buf);
1294 enable_async_io ();
1297 void
1298 dead_thread_notify (int id)
1300 char own_buf[256];
1302 /* The `x' response is not yet part of the remote protocol. Do nothing. */
1303 if (1)
1304 return;
1306 sprintf (own_buf, "x%x", id);
1307 disable_async_io ();
1308 putpkt (own_buf);
1309 enable_async_io ();
1312 void
1313 prepare_resume_reply (char *buf, ptid_t ptid,
1314 struct target_waitstatus *status)
1316 if (debug_threads)
1317 fprintf (stderr, "Writing resume reply for %s:%d\n",
1318 target_pid_to_str (ptid), status->kind);
1320 switch (status->kind)
1322 case TARGET_WAITKIND_STOPPED:
1324 struct thread_info *saved_inferior;
1325 const char **regp;
1326 struct regcache *regcache;
1328 sprintf (buf, "T%02x", status->value.sig);
1329 buf += strlen (buf);
1331 regp = gdbserver_expedite_regs;
1333 saved_inferior = current_inferior;
1335 current_inferior = find_thread_ptid (ptid);
1337 regcache = get_thread_regcache (current_inferior, 1);
1339 if (the_target->stopped_by_watchpoint != NULL
1340 && (*the_target->stopped_by_watchpoint) ())
1342 CORE_ADDR addr;
1343 int i;
1345 strncpy (buf, "watch:", 6);
1346 buf += 6;
1348 addr = (*the_target->stopped_data_address) ();
1350 /* Convert each byte of the address into two hexadecimal
1351 chars. Note that we take sizeof (void *) instead of
1352 sizeof (addr); this is to avoid sending a 64-bit
1353 address to a 32-bit GDB. */
1354 for (i = sizeof (void *) * 2; i > 0; i--)
1355 *buf++ = tohex ((addr >> (i - 1) * 4) & 0xf);
1356 *buf++ = ';';
1359 while (*regp)
1361 buf = outreg (regcache, find_regno (*regp), buf);
1362 regp ++;
1364 *buf = '\0';
1366 /* Formerly, if the debugger had not used any thread features
1367 we would not burden it with a thread status response. This
1368 was for the benefit of GDB 4.13 and older. However, in
1369 recent GDB versions the check (``if (cont_thread != 0)'')
1370 does not have the desired effect because of sillyness in
1371 the way that the remote protocol handles specifying a
1372 thread. Since thread support relies on qSymbol support
1373 anyway, assume GDB can handle threads. */
1375 if (using_threads && !disable_packet_Tthread)
1377 /* This if (1) ought to be unnecessary. But remote_wait
1378 in GDB will claim this event belongs to inferior_ptid
1379 if we do not specify a thread, and there's no way for
1380 gdbserver to know what inferior_ptid is. */
1381 if (1 || !ptid_equal (general_thread, ptid))
1383 int core = -1;
1384 /* In non-stop, don't change the general thread behind
1385 GDB's back. */
1386 if (!non_stop)
1387 general_thread = ptid;
1388 sprintf (buf, "thread:");
1389 buf += strlen (buf);
1390 buf = write_ptid (buf, ptid);
1391 strcat (buf, ";");
1392 buf += strlen (buf);
1394 core = target_core_of_thread (ptid);
1396 if (core != -1)
1398 sprintf (buf, "core:");
1399 buf += strlen (buf);
1400 sprintf (buf, "%x", core);
1401 strcat (buf, ";");
1402 buf += strlen (buf);
1407 if (dlls_changed)
1409 strcpy (buf, "library:;");
1410 buf += strlen (buf);
1411 dlls_changed = 0;
1414 current_inferior = saved_inferior;
1416 break;
1417 case TARGET_WAITKIND_EXITED:
1418 if (multi_process)
1419 sprintf (buf, "W%x;process:%x",
1420 status->value.integer, ptid_get_pid (ptid));
1421 else
1422 sprintf (buf, "W%02x", status->value.integer);
1423 break;
1424 case TARGET_WAITKIND_SIGNALLED:
1425 if (multi_process)
1426 sprintf (buf, "X%x;process:%x",
1427 status->value.sig, ptid_get_pid (ptid));
1428 else
1429 sprintf (buf, "X%02x", status->value.sig);
1430 break;
1431 default:
1432 error ("unhandled waitkind");
1433 break;
1437 void
1438 decode_m_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr)
1440 int i = 0, j = 0;
1441 char ch;
1442 *mem_addr_ptr = *len_ptr = 0;
1444 while ((ch = from[i++]) != ',')
1446 *mem_addr_ptr = *mem_addr_ptr << 4;
1447 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1450 for (j = 0; j < 4; j++)
1452 if ((ch = from[i++]) == 0)
1453 break;
1454 *len_ptr = *len_ptr << 4;
1455 *len_ptr |= fromhex (ch) & 0x0f;
1459 void
1460 decode_M_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr,
1461 unsigned char **to_p)
1463 int i = 0;
1464 char ch;
1465 *mem_addr_ptr = *len_ptr = 0;
1467 while ((ch = from[i++]) != ',')
1469 *mem_addr_ptr = *mem_addr_ptr << 4;
1470 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1473 while ((ch = from[i++]) != ':')
1475 *len_ptr = *len_ptr << 4;
1476 *len_ptr |= fromhex (ch) & 0x0f;
1479 if (*to_p == NULL)
1480 *to_p = xmalloc (*len_ptr);
1482 convert_ascii_to_int (&from[i++], *to_p, *len_ptr);
1486 decode_X_packet (char *from, int packet_len, CORE_ADDR *mem_addr_ptr,
1487 unsigned int *len_ptr, unsigned char **to_p)
1489 int i = 0;
1490 char ch;
1491 *mem_addr_ptr = *len_ptr = 0;
1493 while ((ch = from[i++]) != ',')
1495 *mem_addr_ptr = *mem_addr_ptr << 4;
1496 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1499 while ((ch = from[i++]) != ':')
1501 *len_ptr = *len_ptr << 4;
1502 *len_ptr |= fromhex (ch) & 0x0f;
1505 if (*to_p == NULL)
1506 *to_p = xmalloc (*len_ptr);
1508 if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len - i,
1509 *to_p, *len_ptr) != *len_ptr)
1510 return -1;
1512 return 0;
1515 /* Decode a qXfer write request. */
1518 decode_xfer_write (char *buf, int packet_len, CORE_ADDR *offset,
1519 unsigned int *len, unsigned char *data)
1521 char ch;
1522 char *b = buf;
1524 /* Extract the offset. */
1525 *offset = 0;
1526 while ((ch = *buf++) != ':')
1528 *offset = *offset << 4;
1529 *offset |= fromhex (ch) & 0x0f;
1532 /* Get encoded data. */
1533 packet_len -= buf - b;
1534 *len = remote_unescape_input ((const gdb_byte *) buf, packet_len,
1535 data, packet_len);
1536 return 0;
1539 /* Decode the parameters of a qSearch:memory packet. */
1542 decode_search_memory_packet (const char *buf, int packet_len,
1543 CORE_ADDR *start_addrp,
1544 CORE_ADDR *search_space_lenp,
1545 gdb_byte *pattern, unsigned int *pattern_lenp)
1547 const char *p = buf;
1549 p = decode_address_to_semicolon (start_addrp, p);
1550 p = decode_address_to_semicolon (search_space_lenp, p);
1551 packet_len -= p - buf;
1552 *pattern_lenp = remote_unescape_input ((const gdb_byte *) p, packet_len,
1553 pattern, packet_len);
1554 return 0;
1557 static void
1558 free_sym_cache (struct sym_cache *sym)
1560 if (sym != NULL)
1562 free (sym->name);
1563 free (sym);
1567 void
1568 clear_symbol_cache (struct sym_cache **symcache_p)
1570 struct sym_cache *sym, *next;
1572 /* Check the cache first. */
1573 for (sym = *symcache_p; sym; sym = next)
1575 next = sym->next;
1576 free_sym_cache (sym);
1579 *symcache_p = NULL;
1582 /* Get the address of NAME, and return it in ADDRP if found. if
1583 MAY_ASK_GDB is false, assume symbol cache misses are failures.
1584 Returns 1 if the symbol is found, 0 if it is not, -1 on error. */
1587 look_up_one_symbol (const char *name, CORE_ADDR *addrp, int may_ask_gdb)
1589 char own_buf[266], *p, *q;
1590 int len;
1591 struct sym_cache *sym;
1592 struct process_info *proc;
1594 proc = current_process ();
1596 /* Check the cache first. */
1597 for (sym = proc->symbol_cache; sym; sym = sym->next)
1598 if (strcmp (name, sym->name) == 0)
1600 *addrp = sym->addr;
1601 return 1;
1604 /* It might not be an appropriate time to look up a symbol,
1605 e.g. while we're trying to fetch registers. */
1606 if (!may_ask_gdb)
1607 return 0;
1609 /* Send the request. */
1610 strcpy (own_buf, "qSymbol:");
1611 hexify (own_buf + strlen ("qSymbol:"), name, strlen (name));
1612 if (putpkt (own_buf) < 0)
1613 return -1;
1615 /* FIXME: Eventually add buffer overflow checking (to getpkt?) */
1616 len = getpkt (own_buf);
1617 if (len < 0)
1618 return -1;
1620 /* We ought to handle pretty much any packet at this point while we
1621 wait for the qSymbol "response". That requires re-entering the
1622 main loop. For now, this is an adequate approximation; allow
1623 GDB to read from memory while it figures out the address of the
1624 symbol. */
1625 while (own_buf[0] == 'm')
1627 CORE_ADDR mem_addr;
1628 unsigned char *mem_buf;
1629 unsigned int mem_len;
1631 decode_m_packet (&own_buf[1], &mem_addr, &mem_len);
1632 mem_buf = xmalloc (mem_len);
1633 if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
1634 convert_int_to_ascii (mem_buf, own_buf, mem_len);
1635 else
1636 write_enn (own_buf);
1637 free (mem_buf);
1638 if (putpkt (own_buf) < 0)
1639 return -1;
1640 len = getpkt (own_buf);
1641 if (len < 0)
1642 return -1;
1645 if (strncmp (own_buf, "qSymbol:", strlen ("qSymbol:")) != 0)
1647 warning ("Malformed response to qSymbol, ignoring: %s\n", own_buf);
1648 return -1;
1651 p = own_buf + strlen ("qSymbol:");
1652 q = p;
1653 while (*q && *q != ':')
1654 q++;
1656 /* Make sure we found a value for the symbol. */
1657 if (p == q || *q == '\0')
1658 return 0;
1660 decode_address (addrp, p, q - p);
1662 /* Save the symbol in our cache. */
1663 sym = xmalloc (sizeof (*sym));
1664 sym->name = xstrdup (name);
1665 sym->addr = *addrp;
1666 sym->next = proc->symbol_cache;
1667 proc->symbol_cache = sym;
1669 return 1;
1672 /* Relocate an instruction to execute at a different address. OLDLOC
1673 is the address in the inferior memory where the instruction to
1674 relocate is currently at. On input, TO points to the destination
1675 where we want the instruction to be copied (and possibly adjusted)
1676 to. On output, it points to one past the end of the resulting
1677 instruction(s). The effect of executing the instruction at TO
1678 shall be the same as if executing it at OLDLOC. For example, call
1679 instructions that implicitly push the return address on the stack
1680 should be adjusted to return to the instruction after OLDLOC;
1681 relative branches, and other PC-relative instructions need the
1682 offset adjusted; etc. Returns 0 on success, -1 on failure. */
1685 relocate_instruction (CORE_ADDR *to, CORE_ADDR oldloc)
1687 char own_buf[266];
1688 int len;
1689 ULONGEST written = 0;
1691 /* Send the request. */
1692 strcpy (own_buf, "qRelocInsn:");
1693 sprintf (own_buf, "qRelocInsn:%s;%s", paddress (oldloc),
1694 paddress (*to));
1695 if (putpkt (own_buf) < 0)
1696 return -1;
1698 /* FIXME: Eventually add buffer overflow checking (to getpkt?) */
1699 len = getpkt (own_buf);
1700 if (len < 0)
1701 return -1;
1703 /* We ought to handle pretty much any packet at this point while we
1704 wait for the qRelocInsn "response". That requires re-entering
1705 the main loop. For now, this is an adequate approximation; allow
1706 GDB to access memory. */
1707 while (own_buf[0] == 'm' || own_buf[0] == 'M' || own_buf[0] == 'X')
1709 CORE_ADDR mem_addr;
1710 unsigned char *mem_buf = NULL;
1711 unsigned int mem_len;
1713 if (own_buf[0] == 'm')
1715 decode_m_packet (&own_buf[1], &mem_addr, &mem_len);
1716 mem_buf = xmalloc (mem_len);
1717 if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
1718 convert_int_to_ascii (mem_buf, own_buf, mem_len);
1719 else
1720 write_enn (own_buf);
1722 else if (own_buf[0] == 'X')
1724 if (decode_X_packet (&own_buf[1], len - 1, &mem_addr,
1725 &mem_len, &mem_buf) < 0
1726 || write_inferior_memory (mem_addr, mem_buf, mem_len) != 0)
1727 write_enn (own_buf);
1728 else
1729 write_ok (own_buf);
1731 else
1733 decode_M_packet (&own_buf[1], &mem_addr, &mem_len, &mem_buf);
1734 if (write_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
1735 write_ok (own_buf);
1736 else
1737 write_enn (own_buf);
1739 free (mem_buf);
1740 if (putpkt (own_buf) < 0)
1741 return -1;
1742 len = getpkt (own_buf);
1743 if (len < 0)
1744 return -1;
1747 if (own_buf[0] == 'E')
1749 warning ("An error occurred while relocating an instruction: %s\n",
1750 own_buf);
1751 return -1;
1754 if (strncmp (own_buf, "qRelocInsn:", strlen ("qRelocInsn:")) != 0)
1756 warning ("Malformed response to qRelocInsn, ignoring: %s\n",
1757 own_buf);
1758 return -1;
1761 unpack_varlen_hex (own_buf + strlen ("qRelocInsn:"), &written);
1763 *to += written;
1764 return 0;
1767 void
1768 monitor_output (const char *msg)
1770 char *buf = xmalloc (strlen (msg) * 2 + 2);
1772 buf[0] = 'O';
1773 hexify (buf + 1, msg, 0);
1775 putpkt (buf);
1776 free (buf);
1779 #endif