gdb: Make GMP a required dependency for building GDB
[binutils-gdb.git] / gdbserver / remote-utils.cc
blob5a6ceb1d9a109b8c9df75eb605e226dd9ce993aa
1 /* Remote utility routines for the remote server for GDB.
2 Copyright (C) 1986-2020 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 #if HAVE_TERMIOS_H
21 #include <termios.h>
22 #endif
23 #include "target.h"
24 #include "gdbthread.h"
25 #include "tdesc.h"
26 #include "debug.h"
27 #include "dll.h"
28 #include "gdbsupport/rsp-low.h"
29 #include "gdbsupport/netstuff.h"
30 #include "gdbsupport/filestuff.h"
31 #include "gdbsupport/gdb-sigmask.h"
32 #include <ctype.h>
33 #if HAVE_SYS_IOCTL_H
34 #include <sys/ioctl.h>
35 #endif
36 #if HAVE_SYS_FILE_H
37 #include <sys/file.h>
38 #endif
39 #if HAVE_NETINET_IN_H
40 #include <netinet/in.h>
41 #endif
42 #if HAVE_SYS_SOCKET_H
43 #include <sys/socket.h>
44 #endif
45 #if HAVE_NETDB_H
46 #include <netdb.h>
47 #endif
48 #if HAVE_NETINET_TCP_H
49 #include <netinet/tcp.h>
50 #endif
51 #if HAVE_SYS_IOCTL_H
52 #include <sys/ioctl.h>
53 #endif
54 #if HAVE_SIGNAL_H
55 #include <signal.h>
56 #endif
57 #if HAVE_FCNTL_H
58 #include <fcntl.h>
59 #endif
60 #include "gdbsupport/gdb_sys_time.h"
61 #include <unistd.h>
62 #if HAVE_ARPA_INET_H
63 #include <arpa/inet.h>
64 #endif
65 #include <sys/stat.h>
67 #if USE_WIN32API
68 #include <ws2tcpip.h>
69 #endif
71 #ifndef HAVE_SOCKLEN_T
72 typedef int socklen_t;
73 #endif
75 #ifndef IN_PROCESS_AGENT
77 /* Extra value for readchar_callback. */
78 enum {
79 /* The callback is currently not scheduled. */
80 NOT_SCHEDULED = -1
83 /* Status of the readchar callback.
84 Either NOT_SCHEDULED or the callback id. */
85 static int readchar_callback = NOT_SCHEDULED;
87 static int readchar (void);
88 static void reset_readchar (void);
89 static void reschedule (void);
91 /* A cache entry for a successfully looked-up symbol. */
92 struct sym_cache
94 char *name;
95 CORE_ADDR addr;
96 struct sym_cache *next;
99 static int remote_is_stdio = 0;
101 static int remote_desc = -1;
102 static int listen_desc = -1;
104 #ifdef USE_WIN32API
105 # define read(fd, buf, len) recv (fd, (char *) buf, len, 0)
106 # define write(fd, buf, len) send (fd, (char *) buf, len, 0)
107 #endif
110 gdb_connected (void)
112 return remote_desc != -1;
115 /* Return true if the remote connection is over stdio. */
118 remote_connection_is_stdio (void)
120 return remote_is_stdio;
123 static void
124 enable_async_notification (int fd)
126 #if defined(F_SETFL) && defined (FASYNC)
127 int save_fcntl_flags;
129 save_fcntl_flags = fcntl (fd, F_GETFL, 0);
130 fcntl (fd, F_SETFL, save_fcntl_flags | FASYNC);
131 #if defined (F_SETOWN)
132 fcntl (fd, F_SETOWN, getpid ());
133 #endif
134 #endif
137 static void
138 handle_accept_event (int err, gdb_client_data client_data)
140 struct sockaddr_storage sockaddr;
141 socklen_t len = sizeof (sockaddr);
143 if (debug_threads)
144 debug_printf ("handling possible accept event\n");
146 remote_desc = accept (listen_desc, (struct sockaddr *) &sockaddr, &len);
147 if (remote_desc == -1)
148 perror_with_name ("Accept failed");
150 /* Enable TCP keep alive process. */
151 socklen_t tmp = 1;
152 setsockopt (remote_desc, SOL_SOCKET, SO_KEEPALIVE,
153 (char *) &tmp, sizeof (tmp));
155 /* Tell TCP not to delay small packets. This greatly speeds up
156 interactive response. */
157 tmp = 1;
158 setsockopt (remote_desc, IPPROTO_TCP, TCP_NODELAY,
159 (char *) &tmp, sizeof (tmp));
161 #ifndef USE_WIN32API
162 signal (SIGPIPE, SIG_IGN); /* If we don't do this, then gdbserver simply
163 exits when the remote side dies. */
164 #endif
166 if (run_once)
168 #ifndef USE_WIN32API
169 close (listen_desc); /* No longer need this */
170 #else
171 closesocket (listen_desc); /* No longer need this */
172 #endif
175 /* Even if !RUN_ONCE no longer notice new connections. Still keep the
176 descriptor open for add_file_handler to wait for a new connection. */
177 delete_file_handler (listen_desc);
179 /* Convert IP address to string. */
180 char orig_host[GDB_NI_MAX_ADDR], orig_port[GDB_NI_MAX_PORT];
182 int r = getnameinfo ((struct sockaddr *) &sockaddr, len,
183 orig_host, sizeof (orig_host),
184 orig_port, sizeof (orig_port),
185 NI_NUMERICHOST | NI_NUMERICSERV);
187 if (r != 0)
188 fprintf (stderr, _("Could not obtain remote address: %s\n"),
189 gai_strerror (r));
190 else
191 fprintf (stderr, _("Remote debugging from host %s, port %s\n"),
192 orig_host, orig_port);
194 enable_async_notification (remote_desc);
196 /* Register the event loop handler. */
197 add_file_handler (remote_desc, handle_serial_event, NULL, "remote-net");
199 /* We have a new GDB connection now. If we were disconnected
200 tracing, there's a window where the target could report a stop
201 event to the event loop, and since we have a connection now, we'd
202 try to send vStopped notifications to GDB. But, don't do that
203 until GDB as selected all-stop/non-stop, and has queried the
204 threads' status ('?'). */
205 target_async (0);
208 /* Prepare for a later connection to a remote debugger.
209 NAME is the filename used for communication. */
211 void
212 remote_prepare (const char *name)
214 client_state &cs = get_client_state ();
215 #ifdef USE_WIN32API
216 static int winsock_initialized;
217 #endif
218 socklen_t tmp;
220 remote_is_stdio = 0;
221 if (strcmp (name, STDIO_CONNECTION_NAME) == 0)
223 /* We need to record fact that we're using stdio sooner than the
224 call to remote_open so start_inferior knows the connection is
225 via stdio. */
226 remote_is_stdio = 1;
227 cs.transport_is_reliable = 1;
228 return;
231 struct addrinfo hint;
232 struct addrinfo *ainfo;
234 memset (&hint, 0, sizeof (hint));
235 /* Assume no prefix will be passed, therefore we should use
236 AF_UNSPEC. */
237 hint.ai_family = AF_UNSPEC;
238 hint.ai_socktype = SOCK_STREAM;
239 hint.ai_protocol = IPPROTO_TCP;
241 parsed_connection_spec parsed
242 = parse_connection_spec_without_prefix (name, &hint);
244 if (parsed.port_str.empty ())
246 cs.transport_is_reliable = 0;
247 return;
250 #ifdef USE_WIN32API
251 if (!winsock_initialized)
253 WSADATA wsad;
255 WSAStartup (MAKEWORD (1, 0), &wsad);
256 winsock_initialized = 1;
258 #endif
260 int r = getaddrinfo (parsed.host_str.c_str (), parsed.port_str.c_str (),
261 &hint, &ainfo);
263 if (r != 0)
264 error (_("%s: cannot resolve name: %s"), name, gai_strerror (r));
266 scoped_free_addrinfo freeaddrinfo (ainfo);
268 struct addrinfo *iter;
270 for (iter = ainfo; iter != NULL; iter = iter->ai_next)
272 listen_desc = gdb_socket_cloexec (iter->ai_family, iter->ai_socktype,
273 iter->ai_protocol);
275 if (listen_desc >= 0)
276 break;
279 if (iter == NULL)
280 perror_with_name ("Can't open socket");
282 /* Allow rapid reuse of this port. */
283 tmp = 1;
284 setsockopt (listen_desc, SOL_SOCKET, SO_REUSEADDR, (char *) &tmp,
285 sizeof (tmp));
287 switch (iter->ai_family)
289 case AF_INET:
290 ((struct sockaddr_in *) iter->ai_addr)->sin_addr.s_addr = INADDR_ANY;
291 break;
292 case AF_INET6:
293 ((struct sockaddr_in6 *) iter->ai_addr)->sin6_addr = in6addr_any;
294 break;
295 default:
296 internal_error (__FILE__, __LINE__,
297 _("Invalid 'ai_family' %d\n"), iter->ai_family);
300 if (bind (listen_desc, iter->ai_addr, iter->ai_addrlen) != 0)
301 perror_with_name ("Can't bind address");
303 if (listen (listen_desc, 1) != 0)
304 perror_with_name ("Can't listen on socket");
306 cs.transport_is_reliable = 1;
309 /* Open a connection to a remote debugger.
310 NAME is the filename used for communication. */
312 void
313 remote_open (const char *name)
315 const char *port_str;
317 port_str = strchr (name, ':');
318 #ifdef USE_WIN32API
319 if (port_str == NULL)
320 error ("Only HOST:PORT is supported on this platform.");
321 #endif
323 if (strcmp (name, STDIO_CONNECTION_NAME) == 0)
325 fprintf (stderr, "Remote debugging using stdio\n");
327 /* Use stdin as the handle of the connection.
328 We only select on reads, for example. */
329 remote_desc = fileno (stdin);
331 enable_async_notification (remote_desc);
333 /* Register the event loop handler. */
334 add_file_handler (remote_desc, handle_serial_event, NULL, "remote-stdio");
336 #ifndef USE_WIN32API
337 else if (port_str == NULL)
339 struct stat statbuf;
341 if (stat (name, &statbuf) == 0
342 && (S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode)))
343 remote_desc = open (name, O_RDWR);
344 else
346 errno = EINVAL;
347 remote_desc = -1;
350 if (remote_desc < 0)
351 perror_with_name ("Could not open remote device");
353 #if HAVE_TERMIOS_H
355 struct termios termios;
356 tcgetattr (remote_desc, &termios);
358 termios.c_iflag = 0;
359 termios.c_oflag = 0;
360 termios.c_lflag = 0;
361 termios.c_cflag &= ~(CSIZE | PARENB);
362 termios.c_cflag |= CLOCAL | CS8;
363 termios.c_cc[VMIN] = 1;
364 termios.c_cc[VTIME] = 0;
366 tcsetattr (remote_desc, TCSANOW, &termios);
368 #endif
370 fprintf (stderr, "Remote debugging using %s\n", name);
372 enable_async_notification (remote_desc);
374 /* Register the event loop handler. */
375 add_file_handler (remote_desc, handle_serial_event, NULL,
376 "remote-device");
378 #endif /* USE_WIN32API */
379 else
381 char listen_port[GDB_NI_MAX_PORT];
382 struct sockaddr_storage sockaddr;
383 socklen_t len = sizeof (sockaddr);
385 if (getsockname (listen_desc, (struct sockaddr *) &sockaddr, &len) < 0)
386 perror_with_name ("Can't determine port");
388 int r = getnameinfo ((struct sockaddr *) &sockaddr, len,
389 NULL, 0,
390 listen_port, sizeof (listen_port),
391 NI_NUMERICSERV);
393 if (r != 0)
394 fprintf (stderr, _("Can't obtain port where we are listening: %s"),
395 gai_strerror (r));
396 else
397 fprintf (stderr, _("Listening on port %s\n"), listen_port);
399 fflush (stderr);
401 /* Register the event loop handler. */
402 add_file_handler (listen_desc, handle_accept_event, NULL,
403 "remote-listen");
407 void
408 remote_close (void)
410 delete_file_handler (remote_desc);
412 disable_async_io ();
414 #ifdef USE_WIN32API
415 closesocket (remote_desc);
416 #else
417 if (! remote_connection_is_stdio ())
418 close (remote_desc);
419 #endif
420 remote_desc = -1;
422 reset_readchar ();
425 #endif
427 #ifndef IN_PROCESS_AGENT
429 void
430 decode_address (CORE_ADDR *addrp, const char *start, int len)
432 CORE_ADDR addr;
433 char ch;
434 int i;
436 addr = 0;
437 for (i = 0; i < len; i++)
439 ch = start[i];
440 addr = addr << 4;
441 addr = addr | (fromhex (ch) & 0x0f);
443 *addrp = addr;
446 const char *
447 decode_address_to_semicolon (CORE_ADDR *addrp, const char *start)
449 const char *end;
451 end = start;
452 while (*end != '\0' && *end != ';')
453 end++;
455 decode_address (addrp, start, end - start);
457 if (*end == ';')
458 end++;
459 return end;
462 #endif
464 #ifndef IN_PROCESS_AGENT
466 /* Look for a sequence of characters which can be run-length encoded.
467 If there are any, update *CSUM and *P. Otherwise, output the
468 single character. Return the number of characters consumed. */
470 static int
471 try_rle (char *buf, int remaining, unsigned char *csum, char **p)
473 int n;
475 /* Always output the character. */
476 *csum += buf[0];
477 *(*p)++ = buf[0];
479 /* Don't go past '~'. */
480 if (remaining > 97)
481 remaining = 97;
483 for (n = 1; n < remaining; n++)
484 if (buf[n] != buf[0])
485 break;
487 /* N is the index of the first character not the same as buf[0].
488 buf[0] is counted twice, so by decrementing N, we get the number
489 of characters the RLE sequence will replace. */
490 n--;
492 if (n < 3)
493 return 1;
495 /* Skip the frame characters. The manual says to skip '+' and '-'
496 also, but there's no reason to. Unfortunately these two unusable
497 characters double the encoded length of a four byte zero
498 value. */
499 while (n + 29 == '$' || n + 29 == '#')
500 n--;
502 *csum += '*';
503 *(*p)++ = '*';
504 *csum += n + 29;
505 *(*p)++ = n + 29;
507 return n + 1;
510 #endif
512 #ifndef IN_PROCESS_AGENT
514 /* Write a PTID to BUF. Returns BUF+CHARACTERS_WRITTEN. */
516 char *
517 write_ptid (char *buf, ptid_t ptid)
519 client_state &cs = get_client_state ();
520 int pid, tid;
522 if (cs.multi_process)
524 pid = ptid.pid ();
525 if (pid < 0)
526 buf += sprintf (buf, "p-%x.", -pid);
527 else
528 buf += sprintf (buf, "p%x.", pid);
530 tid = ptid.lwp ();
531 if (tid < 0)
532 buf += sprintf (buf, "-%x", -tid);
533 else
534 buf += sprintf (buf, "%x", tid);
536 return buf;
539 static ULONGEST
540 hex_or_minus_one (const char *buf, const char **obuf)
542 ULONGEST ret;
544 if (startswith (buf, "-1"))
546 ret = (ULONGEST) -1;
547 buf += 2;
549 else
550 buf = unpack_varlen_hex (buf, &ret);
552 if (obuf)
553 *obuf = buf;
555 return ret;
558 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
559 passed the last parsed char. Returns null_ptid on error. */
560 ptid_t
561 read_ptid (const char *buf, const char **obuf)
563 const char *p = buf;
564 const char *pp;
565 ULONGEST pid = 0, tid = 0;
567 if (*p == 'p')
569 /* Multi-process ptid. */
570 pp = unpack_varlen_hex (p + 1, &pid);
571 if (*pp != '.')
572 error ("invalid remote ptid: %s\n", p);
574 p = pp + 1;
576 tid = hex_or_minus_one (p, &pp);
578 if (obuf)
579 *obuf = pp;
580 return ptid_t (pid, tid, 0);
583 /* No multi-process. Just a tid. */
584 tid = hex_or_minus_one (p, &pp);
586 /* Since GDB is not sending a process id (multi-process extensions
587 are off), then there's only one process. Default to the first in
588 the list. */
589 pid = pid_of (get_first_process ());
591 if (obuf)
592 *obuf = pp;
593 return ptid_t (pid, tid, 0);
596 /* Write COUNT bytes in BUF to the client.
597 The result is the number of bytes written or -1 if error.
598 This may return less than COUNT. */
600 static int
601 write_prim (const void *buf, int count)
603 if (remote_connection_is_stdio ())
604 return write (fileno (stdout), buf, count);
605 else
606 return write (remote_desc, buf, count);
609 /* Read COUNT bytes from the client and store in BUF.
610 The result is the number of bytes read or -1 if error.
611 This may return less than COUNT. */
613 static int
614 read_prim (void *buf, int count)
616 if (remote_connection_is_stdio ())
617 return read (fileno (stdin), buf, count);
618 else
619 return read (remote_desc, buf, count);
622 /* Send a packet to the remote machine, with error checking.
623 The data of the packet is in BUF, and the length of the
624 packet is in CNT. Returns >= 0 on success, -1 otherwise. */
626 static int
627 putpkt_binary_1 (char *buf, int cnt, int is_notif)
629 client_state &cs = get_client_state ();
630 int i;
631 unsigned char csum = 0;
632 char *buf2;
633 char *p;
634 int cc;
636 buf2 = (char *) xmalloc (strlen ("$") + cnt + strlen ("#nn") + 1);
638 /* Copy the packet into buffer BUF2, encapsulating it
639 and giving it a checksum. */
641 p = buf2;
642 if (is_notif)
643 *p++ = '%';
644 else
645 *p++ = '$';
647 for (i = 0; i < cnt;)
648 i += try_rle (buf + i, cnt - i, &csum, &p);
650 *p++ = '#';
651 *p++ = tohex ((csum >> 4) & 0xf);
652 *p++ = tohex (csum & 0xf);
654 *p = '\0';
656 /* Send it over and over until we get a positive ack. */
660 if (write_prim (buf2, p - buf2) != p - buf2)
662 perror ("putpkt(write)");
663 free (buf2);
664 return -1;
667 if (cs.noack_mode || is_notif)
669 /* Don't expect an ack then. */
670 if (remote_debug)
672 if (is_notif)
673 debug_printf ("putpkt (\"%s\"); [notif]\n", buf2);
674 else
675 debug_printf ("putpkt (\"%s\"); [noack mode]\n", buf2);
676 debug_flush ();
678 break;
681 if (remote_debug)
683 debug_printf ("putpkt (\"%s\"); [looking for ack]\n", buf2);
684 debug_flush ();
687 cc = readchar ();
689 if (cc < 0)
691 free (buf2);
692 return -1;
695 if (remote_debug)
697 debug_printf ("[received '%c' (0x%x)]\n", cc, cc);
698 debug_flush ();
701 /* Check for an input interrupt while we're here. */
702 if (cc == '\003' && current_thread != NULL)
703 the_target->request_interrupt ();
705 while (cc != '+');
707 free (buf2);
708 return 1; /* Success! */
712 putpkt_binary (char *buf, int cnt)
714 return putpkt_binary_1 (buf, cnt, 0);
717 /* Send a packet to the remote machine, with error checking. The data
718 of the packet is in BUF, and the packet should be a NUL-terminated
719 string. Returns >= 0 on success, -1 otherwise. */
722 putpkt (char *buf)
724 return putpkt_binary (buf, strlen (buf));
728 putpkt_notif (char *buf)
730 return putpkt_binary_1 (buf, strlen (buf), 1);
733 /* Come here when we get an input interrupt from the remote side. This
734 interrupt should only be active while we are waiting for the child to do
735 something. Thus this assumes readchar:bufcnt is 0.
736 About the only thing that should come through is a ^C, which
737 will cause us to request child interruption. */
739 static void
740 input_interrupt (int unused)
742 fd_set readset;
743 struct timeval immediate = { 0, 0 };
745 /* Protect against spurious interrupts. This has been observed to
746 be a problem under NetBSD 1.4 and 1.5. */
748 FD_ZERO (&readset);
749 FD_SET (remote_desc, &readset);
750 if (select (remote_desc + 1, &readset, 0, 0, &immediate) > 0)
752 int cc;
753 char c = 0;
755 cc = read_prim (&c, 1);
757 if (cc == 0)
759 fprintf (stderr, "client connection closed\n");
760 return;
762 else if (cc != 1 || c != '\003')
764 fprintf (stderr, "input_interrupt, count = %d c = %d ", cc, c);
765 if (isprint (c))
766 fprintf (stderr, "('%c')\n", c);
767 else
768 fprintf (stderr, "('\\x%02x')\n", c & 0xff);
769 return;
772 the_target->request_interrupt ();
776 /* Check if the remote side sent us an interrupt request (^C). */
777 void
778 check_remote_input_interrupt_request (void)
780 /* This function may be called before establishing communications,
781 therefore we need to validate the remote descriptor. */
783 if (remote_desc == -1)
784 return;
786 input_interrupt (0);
789 /* Asynchronous I/O support. SIGIO must be unblocked when waiting,
790 in order to accept Control-C from the client, and must be blocked
791 when talking to the client. */
793 static void
794 block_unblock_async_io (int block)
796 #ifndef USE_WIN32API
797 sigset_t sigio_set;
799 sigemptyset (&sigio_set);
800 sigaddset (&sigio_set, SIGIO);
801 gdb_sigmask (block ? SIG_BLOCK : SIG_UNBLOCK, &sigio_set, NULL);
802 #endif
805 /* Current state of asynchronous I/O. */
806 static int async_io_enabled;
808 /* Enable asynchronous I/O. */
809 void
810 enable_async_io (void)
812 if (async_io_enabled)
813 return;
815 block_unblock_async_io (0);
817 async_io_enabled = 1;
820 /* Disable asynchronous I/O. */
821 void
822 disable_async_io (void)
824 if (!async_io_enabled)
825 return;
827 block_unblock_async_io (1);
829 async_io_enabled = 0;
832 void
833 initialize_async_io (void)
835 /* Make sure that async I/O starts blocked. */
836 async_io_enabled = 1;
837 disable_async_io ();
839 /* Install the signal handler. */
840 #ifndef USE_WIN32API
841 signal (SIGIO, input_interrupt);
842 #endif
845 /* Internal buffer used by readchar.
846 These are global to readchar because reschedule_remote needs to be
847 able to tell whether the buffer is empty. */
849 static unsigned char readchar_buf[BUFSIZ];
850 static int readchar_bufcnt = 0;
851 static unsigned char *readchar_bufp;
853 /* Returns next char from remote GDB. -1 if error. */
855 static int
856 readchar (void)
858 int ch;
860 if (readchar_bufcnt == 0)
862 readchar_bufcnt = read_prim (readchar_buf, sizeof (readchar_buf));
864 if (readchar_bufcnt <= 0)
866 if (readchar_bufcnt == 0)
868 if (remote_debug)
869 debug_printf ("readchar: Got EOF\n");
871 else
872 perror ("readchar");
874 return -1;
877 readchar_bufp = readchar_buf;
880 readchar_bufcnt--;
881 ch = *readchar_bufp++;
882 reschedule ();
883 return ch;
886 /* Reset the readchar state machine. */
888 static void
889 reset_readchar (void)
891 readchar_bufcnt = 0;
892 if (readchar_callback != NOT_SCHEDULED)
894 delete_timer (readchar_callback);
895 readchar_callback = NOT_SCHEDULED;
899 /* Process remaining data in readchar_buf. */
901 static void
902 process_remaining (void *context)
904 /* This is a one-shot event. */
905 readchar_callback = NOT_SCHEDULED;
907 if (readchar_bufcnt > 0)
908 handle_serial_event (0, NULL);
911 /* If there is still data in the buffer, queue another event to process it,
912 we can't sleep in select yet. */
914 static void
915 reschedule (void)
917 if (readchar_bufcnt > 0 && readchar_callback == NOT_SCHEDULED)
918 readchar_callback = create_timer (0, process_remaining, NULL);
921 /* Read a packet from the remote machine, with error checking,
922 and store it in BUF. Returns length of packet, or negative if error. */
925 getpkt (char *buf)
927 client_state &cs = get_client_state ();
928 char *bp;
929 unsigned char csum, c1, c2;
930 int c;
932 while (1)
934 csum = 0;
936 while (1)
938 c = readchar ();
940 /* The '\003' may appear before or after each packet, so
941 check for an input interrupt. */
942 if (c == '\003')
944 the_target->request_interrupt ();
945 continue;
948 if (c == '$')
949 break;
950 if (remote_debug)
952 debug_printf ("[getpkt: discarding char '%c']\n", c);
953 debug_flush ();
956 if (c < 0)
957 return -1;
960 bp = buf;
961 while (1)
963 c = readchar ();
964 if (c < 0)
965 return -1;
966 if (c == '#')
967 break;
968 *bp++ = c;
969 csum += c;
971 *bp = 0;
973 c1 = fromhex (readchar ());
974 c2 = fromhex (readchar ());
976 if (csum == (c1 << 4) + c2)
977 break;
979 if (cs.noack_mode)
981 fprintf (stderr,
982 "Bad checksum, sentsum=0x%x, csum=0x%x, "
983 "buf=%s [no-ack-mode, Bad medium?]\n",
984 (c1 << 4) + c2, csum, buf);
985 /* Not much we can do, GDB wasn't expecting an ack/nac. */
986 break;
989 fprintf (stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
990 (c1 << 4) + c2, csum, buf);
991 if (write_prim ("-", 1) != 1)
992 return -1;
995 if (!cs.noack_mode)
997 if (remote_debug)
999 debug_printf ("getpkt (\"%s\"); [sending ack] \n", buf);
1000 debug_flush ();
1003 if (write_prim ("+", 1) != 1)
1004 return -1;
1006 if (remote_debug)
1008 debug_printf ("[sent ack]\n");
1009 debug_flush ();
1012 else
1014 if (remote_debug)
1016 debug_printf ("getpkt (\"%s\"); [no ack sent] \n", buf);
1017 debug_flush ();
1021 /* The readchar above may have already read a '\003' out of the socket
1022 and moved it to the local buffer. For example, when GDB sends
1023 vCont;c immediately followed by interrupt (see
1024 gdb.base/interrupt-noterm.exp). As soon as we see the vCont;c, we'll
1025 resume the inferior and wait. Since we've already moved the '\003'
1026 to the local buffer, SIGIO won't help. In that case, if we don't
1027 check for interrupt after the vCont;c packet, the interrupt character
1028 would stay in the buffer unattended until after the next (unrelated)
1029 stop. */
1030 while (readchar_bufcnt > 0 && *readchar_bufp == '\003')
1032 /* Consume the interrupt character in the buffer. */
1033 readchar ();
1034 the_target->request_interrupt ();
1037 return bp - buf;
1040 void
1041 write_ok (char *buf)
1043 buf[0] = 'O';
1044 buf[1] = 'K';
1045 buf[2] = '\0';
1048 void
1049 write_enn (char *buf)
1051 /* Some day, we should define the meanings of the error codes... */
1052 buf[0] = 'E';
1053 buf[1] = '0';
1054 buf[2] = '1';
1055 buf[3] = '\0';
1058 #endif
1060 #ifndef IN_PROCESS_AGENT
1062 static char *
1063 outreg (struct regcache *regcache, int regno, char *buf)
1065 if ((regno >> 12) != 0)
1066 *buf++ = tohex ((regno >> 12) & 0xf);
1067 if ((regno >> 8) != 0)
1068 *buf++ = tohex ((regno >> 8) & 0xf);
1069 *buf++ = tohex ((regno >> 4) & 0xf);
1070 *buf++ = tohex (regno & 0xf);
1071 *buf++ = ':';
1072 collect_register_as_string (regcache, regno, buf);
1073 buf += 2 * register_size (regcache->tdesc, regno);
1074 *buf++ = ';';
1076 return buf;
1079 void
1080 prepare_resume_reply (char *buf, ptid_t ptid,
1081 struct target_waitstatus *status)
1083 client_state &cs = get_client_state ();
1084 if (debug_threads)
1085 debug_printf ("Writing resume reply for %s:%d\n",
1086 target_pid_to_str (ptid), status->kind);
1088 switch (status->kind)
1090 case TARGET_WAITKIND_STOPPED:
1091 case TARGET_WAITKIND_FORKED:
1092 case TARGET_WAITKIND_VFORKED:
1093 case TARGET_WAITKIND_VFORK_DONE:
1094 case TARGET_WAITKIND_EXECD:
1095 case TARGET_WAITKIND_THREAD_CREATED:
1096 case TARGET_WAITKIND_SYSCALL_ENTRY:
1097 case TARGET_WAITKIND_SYSCALL_RETURN:
1099 struct thread_info *saved_thread;
1100 const char **regp;
1101 struct regcache *regcache;
1103 if ((status->kind == TARGET_WAITKIND_FORKED && cs.report_fork_events)
1104 || (status->kind == TARGET_WAITKIND_VFORKED
1105 && cs.report_vfork_events))
1107 enum gdb_signal signal = GDB_SIGNAL_TRAP;
1108 const char *event = (status->kind == TARGET_WAITKIND_FORKED
1109 ? "fork" : "vfork");
1111 sprintf (buf, "T%02x%s:", signal, event);
1112 buf += strlen (buf);
1113 buf = write_ptid (buf, status->value.related_pid);
1114 strcat (buf, ";");
1116 else if (status->kind == TARGET_WAITKIND_VFORK_DONE
1117 && cs.report_vfork_events)
1119 enum gdb_signal signal = GDB_SIGNAL_TRAP;
1121 sprintf (buf, "T%02xvforkdone:;", signal);
1123 else if (status->kind == TARGET_WAITKIND_EXECD && cs.report_exec_events)
1125 enum gdb_signal signal = GDB_SIGNAL_TRAP;
1126 const char *event = "exec";
1127 char hexified_pathname[PATH_MAX * 2];
1129 sprintf (buf, "T%02x%s:", signal, event);
1130 buf += strlen (buf);
1132 /* Encode pathname to hexified format. */
1133 bin2hex ((const gdb_byte *) status->value.execd_pathname,
1134 hexified_pathname,
1135 strlen (status->value.execd_pathname));
1137 sprintf (buf, "%s;", hexified_pathname);
1138 xfree (status->value.execd_pathname);
1139 status->value.execd_pathname = NULL;
1140 buf += strlen (buf);
1142 else if (status->kind == TARGET_WAITKIND_THREAD_CREATED
1143 && cs.report_thread_events)
1145 enum gdb_signal signal = GDB_SIGNAL_TRAP;
1147 sprintf (buf, "T%02xcreate:;", signal);
1149 else if (status->kind == TARGET_WAITKIND_SYSCALL_ENTRY
1150 || status->kind == TARGET_WAITKIND_SYSCALL_RETURN)
1152 enum gdb_signal signal = GDB_SIGNAL_TRAP;
1153 const char *event = (status->kind == TARGET_WAITKIND_SYSCALL_ENTRY
1154 ? "syscall_entry" : "syscall_return");
1156 sprintf (buf, "T%02x%s:%x;", signal, event,
1157 status->value.syscall_number);
1159 else
1160 sprintf (buf, "T%02x", status->value.sig);
1162 if (disable_packet_T)
1164 /* This is a bit (OK, a lot) of a kludge, however, this isn't
1165 really a user feature, but exists only so GDB can use the
1166 gdbserver to test handling of the 'S' stop reply packet, so
1167 we would rather this code be as simple as possible.
1169 By this point we've started to build the 'T' stop packet,
1170 and it should look like 'Txx....' where 'x' is a hex digit.
1171 An 'S' stop packet always looks like 'Sxx', so all we do
1172 here is convert the buffer from a T packet to an S packet
1173 and the avoid adding any extra content by breaking out. */
1174 gdb_assert (*buf == 'T');
1175 gdb_assert (isxdigit (*(buf + 1)));
1176 gdb_assert (isxdigit (*(buf + 2)));
1177 *buf = 'S';
1178 *(buf + 3) = '\0';
1179 break;
1182 buf += strlen (buf);
1184 saved_thread = current_thread;
1186 switch_to_thread (the_target, ptid);
1188 regp = current_target_desc ()->expedite_regs;
1190 regcache = get_thread_regcache (current_thread, 1);
1192 if (the_target->stopped_by_watchpoint ())
1194 CORE_ADDR addr;
1195 int i;
1197 memcpy (buf, "watch:", 6);
1198 buf += 6;
1200 addr = the_target->stopped_data_address ();
1202 /* Convert each byte of the address into two hexadecimal
1203 chars. Note that we take sizeof (void *) instead of
1204 sizeof (addr); this is to avoid sending a 64-bit
1205 address to a 32-bit GDB. */
1206 for (i = sizeof (void *) * 2; i > 0; i--)
1207 *buf++ = tohex ((addr >> (i - 1) * 4) & 0xf);
1208 *buf++ = ';';
1210 else if (cs.swbreak_feature && target_stopped_by_sw_breakpoint ())
1212 sprintf (buf, "swbreak:;");
1213 buf += strlen (buf);
1215 else if (cs.hwbreak_feature && target_stopped_by_hw_breakpoint ())
1217 sprintf (buf, "hwbreak:;");
1218 buf += strlen (buf);
1221 while (*regp)
1223 buf = outreg (regcache, find_regno (regcache->tdesc, *regp), buf);
1224 regp ++;
1226 *buf = '\0';
1228 /* Formerly, if the debugger had not used any thread features
1229 we would not burden it with a thread status response. This
1230 was for the benefit of GDB 4.13 and older. However, in
1231 recent GDB versions the check (``if (cont_thread != 0)'')
1232 does not have the desired effect because of sillyness in
1233 the way that the remote protocol handles specifying a
1234 thread. Since thread support relies on qSymbol support
1235 anyway, assume GDB can handle threads. */
1237 if (using_threads && !disable_packet_Tthread)
1239 /* This if (1) ought to be unnecessary. But remote_wait
1240 in GDB will claim this event belongs to inferior_ptid
1241 if we do not specify a thread, and there's no way for
1242 gdbserver to know what inferior_ptid is. */
1243 if (1 || cs.general_thread != ptid)
1245 int core = -1;
1246 /* In non-stop, don't change the general thread behind
1247 GDB's back. */
1248 if (!non_stop)
1249 cs.general_thread = ptid;
1250 sprintf (buf, "thread:");
1251 buf += strlen (buf);
1252 buf = write_ptid (buf, ptid);
1253 strcat (buf, ";");
1254 buf += strlen (buf);
1256 core = target_core_of_thread (ptid);
1258 if (core != -1)
1260 sprintf (buf, "core:");
1261 buf += strlen (buf);
1262 sprintf (buf, "%x", core);
1263 strcat (buf, ";");
1264 buf += strlen (buf);
1269 if (dlls_changed)
1271 strcpy (buf, "library:;");
1272 buf += strlen (buf);
1273 dlls_changed = 0;
1276 current_thread = saved_thread;
1278 break;
1279 case TARGET_WAITKIND_EXITED:
1280 if (cs.multi_process)
1281 sprintf (buf, "W%x;process:%x",
1282 status->value.integer, ptid.pid ());
1283 else
1284 sprintf (buf, "W%02x", status->value.integer);
1285 break;
1286 case TARGET_WAITKIND_SIGNALLED:
1287 if (cs.multi_process)
1288 sprintf (buf, "X%x;process:%x",
1289 status->value.sig, ptid.pid ());
1290 else
1291 sprintf (buf, "X%02x", status->value.sig);
1292 break;
1293 case TARGET_WAITKIND_THREAD_EXITED:
1294 sprintf (buf, "w%x;", status->value.integer);
1295 buf += strlen (buf);
1296 buf = write_ptid (buf, ptid);
1297 break;
1298 case TARGET_WAITKIND_NO_RESUMED:
1299 sprintf (buf, "N");
1300 break;
1301 default:
1302 error ("unhandled waitkind");
1303 break;
1307 void
1308 decode_m_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr)
1310 int i = 0, j = 0;
1311 char ch;
1312 *mem_addr_ptr = *len_ptr = 0;
1314 while ((ch = from[i++]) != ',')
1316 *mem_addr_ptr = *mem_addr_ptr << 4;
1317 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1320 for (j = 0; j < 4; j++)
1322 if ((ch = from[i++]) == 0)
1323 break;
1324 *len_ptr = *len_ptr << 4;
1325 *len_ptr |= fromhex (ch) & 0x0f;
1329 void
1330 decode_M_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr,
1331 unsigned char **to_p)
1333 int i = 0;
1334 char ch;
1335 *mem_addr_ptr = *len_ptr = 0;
1337 while ((ch = from[i++]) != ',')
1339 *mem_addr_ptr = *mem_addr_ptr << 4;
1340 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1343 while ((ch = from[i++]) != ':')
1345 *len_ptr = *len_ptr << 4;
1346 *len_ptr |= fromhex (ch) & 0x0f;
1349 if (*to_p == NULL)
1350 *to_p = (unsigned char *) xmalloc (*len_ptr);
1352 hex2bin (&from[i++], *to_p, *len_ptr);
1356 decode_X_packet (char *from, int packet_len, CORE_ADDR *mem_addr_ptr,
1357 unsigned int *len_ptr, unsigned char **to_p)
1359 int i = 0;
1360 char ch;
1361 *mem_addr_ptr = *len_ptr = 0;
1363 while ((ch = from[i++]) != ',')
1365 *mem_addr_ptr = *mem_addr_ptr << 4;
1366 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1369 while ((ch = from[i++]) != ':')
1371 *len_ptr = *len_ptr << 4;
1372 *len_ptr |= fromhex (ch) & 0x0f;
1375 if (*to_p == NULL)
1376 *to_p = (unsigned char *) xmalloc (*len_ptr);
1378 if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len - i,
1379 *to_p, *len_ptr) != *len_ptr)
1380 return -1;
1382 return 0;
1385 /* Decode a qXfer write request. */
1388 decode_xfer_write (char *buf, int packet_len, CORE_ADDR *offset,
1389 unsigned int *len, unsigned char *data)
1391 char ch;
1392 char *b = buf;
1394 /* Extract the offset. */
1395 *offset = 0;
1396 while ((ch = *buf++) != ':')
1398 *offset = *offset << 4;
1399 *offset |= fromhex (ch) & 0x0f;
1402 /* Get encoded data. */
1403 packet_len -= buf - b;
1404 *len = remote_unescape_input ((const gdb_byte *) buf, packet_len,
1405 data, packet_len);
1406 return 0;
1409 /* Decode the parameters of a qSearch:memory packet. */
1412 decode_search_memory_packet (const char *buf, int packet_len,
1413 CORE_ADDR *start_addrp,
1414 CORE_ADDR *search_space_lenp,
1415 gdb_byte *pattern, unsigned int *pattern_lenp)
1417 const char *p = buf;
1419 p = decode_address_to_semicolon (start_addrp, p);
1420 p = decode_address_to_semicolon (search_space_lenp, p);
1421 packet_len -= p - buf;
1422 *pattern_lenp = remote_unescape_input ((const gdb_byte *) p, packet_len,
1423 pattern, packet_len);
1424 return 0;
1427 static void
1428 free_sym_cache (struct sym_cache *sym)
1430 if (sym != NULL)
1432 free (sym->name);
1433 free (sym);
1437 void
1438 clear_symbol_cache (struct sym_cache **symcache_p)
1440 struct sym_cache *sym, *next;
1442 /* Check the cache first. */
1443 for (sym = *symcache_p; sym; sym = next)
1445 next = sym->next;
1446 free_sym_cache (sym);
1449 *symcache_p = NULL;
1452 /* Get the address of NAME, and return it in ADDRP if found. if
1453 MAY_ASK_GDB is false, assume symbol cache misses are failures.
1454 Returns 1 if the symbol is found, 0 if it is not, -1 on error. */
1457 look_up_one_symbol (const char *name, CORE_ADDR *addrp, int may_ask_gdb)
1459 client_state &cs = get_client_state ();
1460 char *p, *q;
1461 int len;
1462 struct sym_cache *sym;
1463 struct process_info *proc;
1465 proc = current_process ();
1467 /* Check the cache first. */
1468 for (sym = proc->symbol_cache; sym; sym = sym->next)
1469 if (strcmp (name, sym->name) == 0)
1471 *addrp = sym->addr;
1472 return 1;
1475 /* It might not be an appropriate time to look up a symbol,
1476 e.g. while we're trying to fetch registers. */
1477 if (!may_ask_gdb)
1478 return 0;
1480 /* Send the request. */
1481 strcpy (cs.own_buf, "qSymbol:");
1482 bin2hex ((const gdb_byte *) name, cs.own_buf + strlen ("qSymbol:"),
1483 strlen (name));
1484 if (putpkt (cs.own_buf) < 0)
1485 return -1;
1487 /* FIXME: Eventually add buffer overflow checking (to getpkt?) */
1488 len = getpkt (cs.own_buf);
1489 if (len < 0)
1490 return -1;
1492 /* We ought to handle pretty much any packet at this point while we
1493 wait for the qSymbol "response". That requires re-entering the
1494 main loop. For now, this is an adequate approximation; allow
1495 GDB to read from memory and handle 'v' packets (for vFile transfers)
1496 while it figures out the address of the symbol. */
1497 while (1)
1499 if (cs.own_buf[0] == 'm')
1501 CORE_ADDR mem_addr;
1502 unsigned char *mem_buf;
1503 unsigned int mem_len;
1505 decode_m_packet (&cs.own_buf[1], &mem_addr, &mem_len);
1506 mem_buf = (unsigned char *) xmalloc (mem_len);
1507 if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
1508 bin2hex (mem_buf, cs.own_buf, mem_len);
1509 else
1510 write_enn (cs.own_buf);
1511 free (mem_buf);
1512 if (putpkt (cs.own_buf) < 0)
1513 return -1;
1515 else if (cs.own_buf[0] == 'v')
1517 int new_len = -1;
1518 handle_v_requests (cs.own_buf, len, &new_len);
1519 if (new_len != -1)
1520 putpkt_binary (cs.own_buf, new_len);
1521 else
1522 putpkt (cs.own_buf);
1524 else
1525 break;
1526 len = getpkt (cs.own_buf);
1527 if (len < 0)
1528 return -1;
1531 if (!startswith (cs.own_buf, "qSymbol:"))
1533 warning ("Malformed response to qSymbol, ignoring: %s", cs.own_buf);
1534 return -1;
1537 p = cs.own_buf + strlen ("qSymbol:");
1538 q = p;
1539 while (*q && *q != ':')
1540 q++;
1542 /* Make sure we found a value for the symbol. */
1543 if (p == q || *q == '\0')
1544 return 0;
1546 decode_address (addrp, p, q - p);
1548 /* Save the symbol in our cache. */
1549 sym = XNEW (struct sym_cache);
1550 sym->name = xstrdup (name);
1551 sym->addr = *addrp;
1552 sym->next = proc->symbol_cache;
1553 proc->symbol_cache = sym;
1555 return 1;
1558 /* Relocate an instruction to execute at a different address. OLDLOC
1559 is the address in the inferior memory where the instruction to
1560 relocate is currently at. On input, TO points to the destination
1561 where we want the instruction to be copied (and possibly adjusted)
1562 to. On output, it points to one past the end of the resulting
1563 instruction(s). The effect of executing the instruction at TO
1564 shall be the same as if executing it at OLDLOC. For example, call
1565 instructions that implicitly push the return address on the stack
1566 should be adjusted to return to the instruction after OLDLOC;
1567 relative branches, and other PC-relative instructions need the
1568 offset adjusted; etc. Returns 0 on success, -1 on failure. */
1571 relocate_instruction (CORE_ADDR *to, CORE_ADDR oldloc)
1573 client_state &cs = get_client_state ();
1574 int len;
1575 ULONGEST written = 0;
1577 /* Send the request. */
1578 sprintf (cs.own_buf, "qRelocInsn:%s;%s", paddress (oldloc),
1579 paddress (*to));
1580 if (putpkt (cs.own_buf) < 0)
1581 return -1;
1583 /* FIXME: Eventually add buffer overflow checking (to getpkt?) */
1584 len = getpkt (cs.own_buf);
1585 if (len < 0)
1586 return -1;
1588 /* We ought to handle pretty much any packet at this point while we
1589 wait for the qRelocInsn "response". That requires re-entering
1590 the main loop. For now, this is an adequate approximation; allow
1591 GDB to access memory. */
1592 while (cs.own_buf[0] == 'm' || cs.own_buf[0] == 'M' || cs.own_buf[0] == 'X')
1594 CORE_ADDR mem_addr;
1595 unsigned char *mem_buf = NULL;
1596 unsigned int mem_len;
1598 if (cs.own_buf[0] == 'm')
1600 decode_m_packet (&cs.own_buf[1], &mem_addr, &mem_len);
1601 mem_buf = (unsigned char *) xmalloc (mem_len);
1602 if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
1603 bin2hex (mem_buf, cs.own_buf, mem_len);
1604 else
1605 write_enn (cs.own_buf);
1607 else if (cs.own_buf[0] == 'X')
1609 if (decode_X_packet (&cs.own_buf[1], len - 1, &mem_addr,
1610 &mem_len, &mem_buf) < 0
1611 || target_write_memory (mem_addr, mem_buf, mem_len) != 0)
1612 write_enn (cs.own_buf);
1613 else
1614 write_ok (cs.own_buf);
1616 else
1618 decode_M_packet (&cs.own_buf[1], &mem_addr, &mem_len, &mem_buf);
1619 if (target_write_memory (mem_addr, mem_buf, mem_len) == 0)
1620 write_ok (cs.own_buf);
1621 else
1622 write_enn (cs.own_buf);
1624 free (mem_buf);
1625 if (putpkt (cs.own_buf) < 0)
1626 return -1;
1627 len = getpkt (cs.own_buf);
1628 if (len < 0)
1629 return -1;
1632 if (cs.own_buf[0] == 'E')
1634 warning ("An error occurred while relocating an instruction: %s",
1635 cs.own_buf);
1636 return -1;
1639 if (!startswith (cs.own_buf, "qRelocInsn:"))
1641 warning ("Malformed response to qRelocInsn, ignoring: %s",
1642 cs.own_buf);
1643 return -1;
1646 unpack_varlen_hex (cs.own_buf + strlen ("qRelocInsn:"), &written);
1648 *to += written;
1649 return 0;
1652 void
1653 monitor_output (const char *msg)
1655 int len = strlen (msg);
1656 char *buf = (char *) xmalloc (len * 2 + 2);
1658 buf[0] = 'O';
1659 bin2hex ((const gdb_byte *) msg, buf + 1, len);
1661 putpkt (buf);
1662 free (buf);
1665 #endif