Fix: A potential null_pointer_deference bug
[binutils-gdb.git] / gdbserver / remote-utils.cc
blobfb5c38d4522339960bb09d531c30ecdcbbb31549
1 /* Remote utility routines for the remote server for GDB.
2 Copyright (C) 1986-2023 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 /* gnulib wraps these as macros, undo them. */
106 # undef read
107 # undef write
109 # define read(fd, buf, len) recv (fd, (char *) buf, len, 0)
110 # define write(fd, buf, len) send (fd, (char *) buf, len, 0)
111 #endif
114 gdb_connected (void)
116 return remote_desc != -1;
119 /* Return true if the remote connection is over stdio. */
122 remote_connection_is_stdio (void)
124 return remote_is_stdio;
127 static void
128 enable_async_notification (int fd)
130 #if defined(F_SETFL) && defined (FASYNC)
131 int save_fcntl_flags;
133 save_fcntl_flags = fcntl (fd, F_GETFL, 0);
134 fcntl (fd, F_SETFL, save_fcntl_flags | FASYNC);
135 #if defined (F_SETOWN)
136 fcntl (fd, F_SETOWN, getpid ());
137 #endif
138 #endif
141 static void
142 handle_accept_event (int err, gdb_client_data client_data)
144 struct sockaddr_storage sockaddr;
145 socklen_t len = sizeof (sockaddr);
147 threads_debug_printf ("handling possible accept event");
149 remote_desc = accept (listen_desc, (struct sockaddr *) &sockaddr, &len);
150 if (remote_desc == -1)
151 perror_with_name ("Accept failed");
153 /* Enable TCP keep alive process. */
154 socklen_t tmp = 1;
155 setsockopt (remote_desc, SOL_SOCKET, SO_KEEPALIVE,
156 (char *) &tmp, sizeof (tmp));
158 /* Tell TCP not to delay small packets. This greatly speeds up
159 interactive response. */
160 tmp = 1;
161 setsockopt (remote_desc, IPPROTO_TCP, TCP_NODELAY,
162 (char *) &tmp, sizeof (tmp));
164 #ifndef USE_WIN32API
165 signal (SIGPIPE, SIG_IGN); /* If we don't do this, then gdbserver simply
166 exits when the remote side dies. */
167 #endif
169 if (run_once)
171 #ifndef USE_WIN32API
172 close (listen_desc); /* No longer need this */
173 #else
174 closesocket (listen_desc); /* No longer need this */
175 #endif
178 /* Even if !RUN_ONCE no longer notice new connections. Still keep the
179 descriptor open for add_file_handler to wait for a new connection. */
180 delete_file_handler (listen_desc);
182 /* Convert IP address to string. */
183 char orig_host[GDB_NI_MAX_ADDR], orig_port[GDB_NI_MAX_PORT];
185 int r = getnameinfo ((struct sockaddr *) &sockaddr, len,
186 orig_host, sizeof (orig_host),
187 orig_port, sizeof (orig_port),
188 NI_NUMERICHOST | NI_NUMERICSERV);
190 if (r != 0)
191 fprintf (stderr, _("Could not obtain remote address: %s\n"),
192 gai_strerror (r));
193 else
194 fprintf (stderr, _("Remote debugging from host %s, port %s\n"),
195 orig_host, orig_port);
197 enable_async_notification (remote_desc);
199 /* Register the event loop handler. */
200 add_file_handler (remote_desc, handle_serial_event, NULL, "remote-net");
202 /* We have a new GDB connection now. If we were disconnected
203 tracing, there's a window where the target could report a stop
204 event to the event loop, and since we have a connection now, we'd
205 try to send vStopped notifications to GDB. But, don't do that
206 until GDB as selected all-stop/non-stop, and has queried the
207 threads' status ('?'). */
208 target_async (0);
211 /* Prepare for a later connection to a remote debugger.
212 NAME is the filename used for communication. */
214 void
215 remote_prepare (const char *name)
217 client_state &cs = get_client_state ();
218 #ifdef USE_WIN32API
219 static int winsock_initialized;
220 #endif
221 socklen_t tmp;
223 remote_is_stdio = 0;
224 if (strcmp (name, STDIO_CONNECTION_NAME) == 0)
226 /* We need to record fact that we're using stdio sooner than the
227 call to remote_open so start_inferior knows the connection is
228 via stdio. */
229 remote_is_stdio = 1;
230 cs.transport_is_reliable = 1;
231 return;
234 struct addrinfo hint;
235 struct addrinfo *ainfo;
237 memset (&hint, 0, sizeof (hint));
238 /* Assume no prefix will be passed, therefore we should use
239 AF_UNSPEC. */
240 hint.ai_family = AF_UNSPEC;
241 hint.ai_socktype = SOCK_STREAM;
242 hint.ai_protocol = IPPROTO_TCP;
244 parsed_connection_spec parsed
245 = parse_connection_spec_without_prefix (name, &hint);
247 if (parsed.port_str.empty ())
249 cs.transport_is_reliable = 0;
250 return;
253 #ifdef USE_WIN32API
254 if (!winsock_initialized)
256 WSADATA wsad;
258 WSAStartup (MAKEWORD (1, 0), &wsad);
259 winsock_initialized = 1;
261 #endif
263 int r = getaddrinfo (parsed.host_str.c_str (), parsed.port_str.c_str (),
264 &hint, &ainfo);
266 if (r != 0)
267 error (_("%s: cannot resolve name: %s"), name, gai_strerror (r));
269 scoped_free_addrinfo freeaddrinfo (ainfo);
271 struct addrinfo *iter;
273 for (iter = ainfo; iter != NULL; iter = iter->ai_next)
275 listen_desc = gdb_socket_cloexec (iter->ai_family, iter->ai_socktype,
276 iter->ai_protocol);
278 if (listen_desc >= 0)
279 break;
282 if (iter == NULL)
283 perror_with_name ("Can't open socket");
285 /* Allow rapid reuse of this port. */
286 tmp = 1;
287 setsockopt (listen_desc, SOL_SOCKET, SO_REUSEADDR, (char *) &tmp,
288 sizeof (tmp));
290 switch (iter->ai_family)
292 case AF_INET:
293 ((struct sockaddr_in *) iter->ai_addr)->sin_addr.s_addr = INADDR_ANY;
294 break;
295 case AF_INET6:
296 ((struct sockaddr_in6 *) iter->ai_addr)->sin6_addr = in6addr_any;
297 break;
298 default:
299 internal_error (_("Invalid 'ai_family' %d\n"), iter->ai_family);
302 if (bind (listen_desc, iter->ai_addr, iter->ai_addrlen) != 0)
303 perror_with_name ("Can't bind address");
305 if (listen (listen_desc, 1) != 0)
306 perror_with_name ("Can't listen on socket");
308 cs.transport_is_reliable = 1;
311 /* Open a connection to a remote debugger.
312 NAME is the filename used for communication. */
314 void
315 remote_open (const char *name)
317 const char *port_str;
319 port_str = strchr (name, ':');
320 #ifdef USE_WIN32API
321 if (port_str == NULL)
322 error ("Only HOST:PORT is supported on this platform.");
323 #endif
325 if (strcmp (name, STDIO_CONNECTION_NAME) == 0)
327 fprintf (stderr, "Remote debugging using stdio\n");
329 /* Use stdin as the handle of the connection.
330 We only select on reads, for example. */
331 remote_desc = fileno (stdin);
333 enable_async_notification (remote_desc);
335 /* Register the event loop handler. */
336 add_file_handler (remote_desc, handle_serial_event, NULL, "remote-stdio");
338 #ifndef USE_WIN32API
339 else if (port_str == NULL)
341 struct stat statbuf;
343 if (stat (name, &statbuf) == 0
344 && (S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode)))
345 remote_desc = open (name, O_RDWR);
346 else
348 errno = EINVAL;
349 remote_desc = -1;
352 if (remote_desc < 0)
353 perror_with_name ("Could not open remote device");
355 #if HAVE_TERMIOS_H
357 struct termios termios;
358 tcgetattr (remote_desc, &termios);
360 termios.c_iflag = 0;
361 termios.c_oflag = 0;
362 termios.c_lflag = 0;
363 termios.c_cflag &= ~(CSIZE | PARENB);
364 termios.c_cflag |= CLOCAL | CS8;
365 termios.c_cc[VMIN] = 1;
366 termios.c_cc[VTIME] = 0;
368 tcsetattr (remote_desc, TCSANOW, &termios);
370 #endif
372 fprintf (stderr, "Remote debugging using %s\n", name);
374 enable_async_notification (remote_desc);
376 /* Register the event loop handler. */
377 add_file_handler (remote_desc, handle_serial_event, NULL,
378 "remote-device");
380 #endif /* USE_WIN32API */
381 else
383 char listen_port[GDB_NI_MAX_PORT];
384 struct sockaddr_storage sockaddr;
385 socklen_t len = sizeof (sockaddr);
387 if (getsockname (listen_desc, (struct sockaddr *) &sockaddr, &len) < 0)
388 perror_with_name ("Can't determine port");
390 int r = getnameinfo ((struct sockaddr *) &sockaddr, len,
391 NULL, 0,
392 listen_port, sizeof (listen_port),
393 NI_NUMERICSERV);
395 if (r != 0)
396 fprintf (stderr, _("Can't obtain port where we are listening: %s"),
397 gai_strerror (r));
398 else
399 fprintf (stderr, _("Listening on port %s\n"), listen_port);
401 fflush (stderr);
403 /* Register the event loop handler. */
404 add_file_handler (listen_desc, handle_accept_event, NULL,
405 "remote-listen");
409 void
410 remote_close (void)
412 delete_file_handler (remote_desc);
414 disable_async_io ();
416 #ifdef USE_WIN32API
417 closesocket (remote_desc);
418 #else
419 if (! remote_connection_is_stdio ())
420 close (remote_desc);
421 #endif
422 remote_desc = -1;
424 reset_readchar ();
427 #endif
429 #ifndef IN_PROCESS_AGENT
431 void
432 decode_address (CORE_ADDR *addrp, const char *start, int len)
434 CORE_ADDR addr;
435 char ch;
436 int i;
438 addr = 0;
439 for (i = 0; i < len; i++)
441 ch = start[i];
442 addr = addr << 4;
443 addr = addr | (fromhex (ch) & 0x0f);
445 *addrp = addr;
448 const char *
449 decode_address_to_semicolon (CORE_ADDR *addrp, const char *start)
451 const char *end;
453 end = start;
454 while (*end != '\0' && *end != ';')
455 end++;
457 decode_address (addrp, start, end - start);
459 if (*end == ';')
460 end++;
461 return end;
464 #endif
466 #ifndef IN_PROCESS_AGENT
468 /* Look for a sequence of characters which can be run-length encoded.
469 If there are any, update *CSUM and *P. Otherwise, output the
470 single character. Return the number of characters consumed. */
472 static int
473 try_rle (char *buf, int remaining, unsigned char *csum, char **p)
475 int n;
477 /* Always output the character. */
478 *csum += buf[0];
479 *(*p)++ = buf[0];
481 /* Don't go past '~'. */
482 if (remaining > 97)
483 remaining = 97;
485 for (n = 1; n < remaining; n++)
486 if (buf[n] != buf[0])
487 break;
489 /* N is the index of the first character not the same as buf[0].
490 buf[0] is counted twice, so by decrementing N, we get the number
491 of characters the RLE sequence will replace. */
492 n--;
494 if (n < 3)
495 return 1;
497 /* Skip the frame characters. The manual says to skip '+' and '-'
498 also, but there's no reason to. Unfortunately these two unusable
499 characters double the encoded length of a four byte zero
500 value. */
501 while (n + 29 == '$' || n + 29 == '#')
502 n--;
504 *csum += '*';
505 *(*p)++ = '*';
506 *csum += n + 29;
507 *(*p)++ = n + 29;
509 return n + 1;
512 #endif
514 #ifndef IN_PROCESS_AGENT
516 /* Write a PTID to BUF. Returns BUF+CHARACTERS_WRITTEN. */
518 char *
519 write_ptid (char *buf, ptid_t ptid)
521 client_state &cs = get_client_state ();
522 int pid, tid;
524 if (cs.multi_process)
526 pid = ptid.pid ();
527 if (pid < 0)
528 buf += sprintf (buf, "p-%x.", -pid);
529 else
530 buf += sprintf (buf, "p%x.", pid);
532 tid = ptid.lwp ();
533 if (tid < 0)
534 buf += sprintf (buf, "-%x", -tid);
535 else
536 buf += sprintf (buf, "%x", tid);
538 return buf;
541 static ULONGEST
542 hex_or_minus_one (const char *buf, const char **obuf)
544 ULONGEST ret;
546 if (startswith (buf, "-1"))
548 ret = (ULONGEST) -1;
549 buf += 2;
551 else
552 buf = unpack_varlen_hex (buf, &ret);
554 if (obuf)
555 *obuf = buf;
557 return ret;
560 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
561 passed the last parsed char. Returns null_ptid on error. */
562 ptid_t
563 read_ptid (const char *buf, const char **obuf)
565 const char *p = buf;
566 const char *pp;
567 ULONGEST pid = 0, tid = 0;
569 if (*p == 'p')
571 /* Multi-process ptid. */
572 pp = unpack_varlen_hex (p + 1, &pid);
573 if (*pp != '.')
574 error ("invalid remote ptid: %s\n", p);
576 p = pp + 1;
578 tid = hex_or_minus_one (p, &pp);
580 if (obuf)
581 *obuf = pp;
582 return ptid_t (pid, tid);
585 /* No multi-process. Just a tid. */
586 tid = hex_or_minus_one (p, &pp);
588 /* Since GDB is not sending a process id (multi-process extensions
589 are off), then there's only one process. Default to the first in
590 the list. */
591 pid = pid_of (get_first_process ());
593 if (obuf)
594 *obuf = pp;
595 return ptid_t (pid, tid);
598 /* Write COUNT bytes in BUF to the client.
599 The result is the number of bytes written or -1 if error.
600 This may return less than COUNT. */
602 static int
603 write_prim (const void *buf, int count)
605 if (remote_connection_is_stdio ())
606 return write (fileno (stdout), buf, count);
607 else
608 return write (remote_desc, buf, count);
611 /* Read COUNT bytes from the client and store in BUF.
612 The result is the number of bytes read or -1 if error.
613 This may return less than COUNT. */
615 static int
616 read_prim (void *buf, int count)
618 if (remote_connection_is_stdio ())
619 return read (fileno (stdin), buf, count);
620 else
621 return read (remote_desc, buf, count);
624 /* Send a packet to the remote machine, with error checking.
625 The data of the packet is in BUF, and the length of the
626 packet is in CNT. Returns >= 0 on success, -1 otherwise. */
628 static int
629 putpkt_binary_1 (char *buf, int cnt, int is_notif)
631 client_state &cs = get_client_state ();
632 int i;
633 unsigned char csum = 0;
634 char *buf2;
635 char *p;
636 int cc;
638 buf2 = (char *) xmalloc (strlen ("$") + cnt + strlen ("#nn") + 1);
640 /* Copy the packet into buffer BUF2, encapsulating it
641 and giving it a checksum. */
643 p = buf2;
644 if (is_notif)
645 *p++ = '%';
646 else
647 *p++ = '$';
649 for (i = 0; i < cnt;)
650 i += try_rle (buf + i, cnt - i, &csum, &p);
652 *p++ = '#';
653 *p++ = tohex ((csum >> 4) & 0xf);
654 *p++ = tohex (csum & 0xf);
656 *p = '\0';
658 /* Send it over and over until we get a positive ack. */
662 if (write_prim (buf2, p - buf2) != p - buf2)
664 perror ("putpkt(write)");
665 free (buf2);
666 return -1;
669 if (cs.noack_mode || is_notif)
671 /* Don't expect an ack then. */
672 if (is_notif)
673 remote_debug_printf ("putpkt (\"%s\"); [notif]", buf2);
674 else
675 remote_debug_printf ("putpkt (\"%s\"); [noack mode]", buf2);
677 break;
680 remote_debug_printf ("putpkt (\"%s\"); [looking for ack]", buf2);
682 cc = readchar ();
684 if (cc < 0)
686 free (buf2);
687 return -1;
690 remote_debug_printf ("[received '%c' (0x%x)]", cc, cc);
692 /* Check for an input interrupt while we're here. */
693 if (cc == '\003' && current_thread != NULL)
694 the_target->request_interrupt ();
696 while (cc != '+');
698 free (buf2);
699 return 1; /* Success! */
703 putpkt_binary (char *buf, int cnt)
705 return putpkt_binary_1 (buf, cnt, 0);
708 /* Send a packet to the remote machine, with error checking. The data
709 of the packet is in BUF, and the packet should be a NUL-terminated
710 string. Returns >= 0 on success, -1 otherwise. */
713 putpkt (char *buf)
715 return putpkt_binary (buf, strlen (buf));
719 putpkt_notif (char *buf)
721 return putpkt_binary_1 (buf, strlen (buf), 1);
724 /* Come here when we get an input interrupt from the remote side. This
725 interrupt should only be active while we are waiting for the child to do
726 something. Thus this assumes readchar:bufcnt is 0.
727 About the only thing that should come through is a ^C, which
728 will cause us to request child interruption. */
730 static void
731 input_interrupt (int unused)
733 fd_set readset;
734 struct timeval immediate = { 0, 0 };
736 /* Protect against spurious interrupts. This has been observed to
737 be a problem under NetBSD 1.4 and 1.5. */
739 FD_ZERO (&readset);
740 FD_SET (remote_desc, &readset);
741 if (select (remote_desc + 1, &readset, 0, 0, &immediate) > 0)
743 int cc;
744 char c = 0;
746 cc = read_prim (&c, 1);
748 if (cc == 0)
750 fprintf (stderr, "client connection closed\n");
751 return;
753 else if (cc != 1 || c != '\003')
755 fprintf (stderr, "input_interrupt, count = %d c = %d ", cc, c);
756 if (isprint (c))
757 fprintf (stderr, "('%c')\n", c);
758 else
759 fprintf (stderr, "('\\x%02x')\n", c & 0xff);
760 return;
763 the_target->request_interrupt ();
767 /* Check if the remote side sent us an interrupt request (^C). */
768 void
769 check_remote_input_interrupt_request (void)
771 /* This function may be called before establishing communications,
772 therefore we need to validate the remote descriptor. */
774 if (remote_desc == -1)
775 return;
777 input_interrupt (0);
780 /* Asynchronous I/O support. SIGIO must be unblocked when waiting,
781 in order to accept Control-C from the client, and must be blocked
782 when talking to the client. */
784 static void
785 block_unblock_async_io (int block)
787 #ifndef USE_WIN32API
788 sigset_t sigio_set;
790 sigemptyset (&sigio_set);
791 sigaddset (&sigio_set, SIGIO);
792 gdb_sigmask (block ? SIG_BLOCK : SIG_UNBLOCK, &sigio_set, NULL);
793 #endif
796 /* Current state of asynchronous I/O. */
797 static int async_io_enabled;
799 /* Enable asynchronous I/O. */
800 void
801 enable_async_io (void)
803 if (async_io_enabled)
804 return;
806 block_unblock_async_io (0);
808 async_io_enabled = 1;
811 /* Disable asynchronous I/O. */
812 void
813 disable_async_io (void)
815 if (!async_io_enabled)
816 return;
818 block_unblock_async_io (1);
820 async_io_enabled = 0;
823 void
824 initialize_async_io (void)
826 /* Make sure that async I/O starts blocked. */
827 async_io_enabled = 1;
828 disable_async_io ();
830 /* Install the signal handler. */
831 #ifndef USE_WIN32API
832 signal (SIGIO, input_interrupt);
833 #endif
836 /* Internal buffer used by readchar.
837 These are global to readchar because reschedule_remote needs to be
838 able to tell whether the buffer is empty. */
840 static unsigned char readchar_buf[BUFSIZ];
841 static int readchar_bufcnt = 0;
842 static unsigned char *readchar_bufp;
844 /* Returns next char from remote GDB. -1 if error. */
846 static int
847 readchar (void)
849 int ch;
851 if (readchar_bufcnt == 0)
853 readchar_bufcnt = read_prim (readchar_buf, sizeof (readchar_buf));
855 if (readchar_bufcnt <= 0)
857 if (readchar_bufcnt == 0)
859 remote_debug_printf ("readchar: Got EOF");
861 else
862 perror ("readchar");
864 return -1;
867 readchar_bufp = readchar_buf;
870 readchar_bufcnt--;
871 ch = *readchar_bufp++;
872 reschedule ();
873 return ch;
876 /* Reset the readchar state machine. */
878 static void
879 reset_readchar (void)
881 readchar_bufcnt = 0;
882 if (readchar_callback != NOT_SCHEDULED)
884 delete_timer (readchar_callback);
885 readchar_callback = NOT_SCHEDULED;
889 /* Process remaining data in readchar_buf. */
891 static void
892 process_remaining (void *context)
894 /* This is a one-shot event. */
895 readchar_callback = NOT_SCHEDULED;
897 if (readchar_bufcnt > 0)
898 handle_serial_event (0, NULL);
901 /* If there is still data in the buffer, queue another event to process it,
902 we can't sleep in select yet. */
904 static void
905 reschedule (void)
907 if (readchar_bufcnt > 0 && readchar_callback == NOT_SCHEDULED)
908 readchar_callback = create_timer (0, process_remaining, NULL);
911 /* Read a packet from the remote machine, with error checking,
912 and store it in BUF. Returns length of packet, or negative if error. */
915 getpkt (char *buf)
917 client_state &cs = get_client_state ();
918 char *bp;
919 unsigned char csum, c1, c2;
920 int c;
922 while (1)
924 csum = 0;
926 while (1)
928 c = readchar ();
930 /* The '\003' may appear before or after each packet, so
931 check for an input interrupt. */
932 if (c == '\003')
934 the_target->request_interrupt ();
935 continue;
938 if (c == '$')
939 break;
941 remote_debug_printf ("[getpkt: discarding char '%c']", c);
943 if (c < 0)
944 return -1;
947 bp = buf;
948 while (1)
950 c = readchar ();
951 if (c < 0)
952 return -1;
953 if (c == '#')
954 break;
955 *bp++ = c;
956 csum += c;
958 *bp = 0;
960 c1 = fromhex (readchar ());
961 c2 = fromhex (readchar ());
963 if (csum == (c1 << 4) + c2)
964 break;
966 if (cs.noack_mode)
968 fprintf (stderr,
969 "Bad checksum, sentsum=0x%x, csum=0x%x, "
970 "buf=%s [no-ack-mode, Bad medium?]\n",
971 (c1 << 4) + c2, csum, buf);
972 /* Not much we can do, GDB wasn't expecting an ack/nac. */
973 break;
976 fprintf (stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
977 (c1 << 4) + c2, csum, buf);
978 if (write_prim ("-", 1) != 1)
979 return -1;
982 if (!cs.noack_mode)
984 remote_debug_printf ("getpkt (\"%s\"); [sending ack]", buf);
986 if (write_prim ("+", 1) != 1)
987 return -1;
989 remote_debug_printf ("[sent ack]");
991 else
992 remote_debug_printf ("getpkt (\"%s\"); [no ack sent]", buf);
994 /* The readchar above may have already read a '\003' out of the socket
995 and moved it to the local buffer. For example, when GDB sends
996 vCont;c immediately followed by interrupt (see
997 gdb.base/interrupt-noterm.exp). As soon as we see the vCont;c, we'll
998 resume the inferior and wait. Since we've already moved the '\003'
999 to the local buffer, SIGIO won't help. In that case, if we don't
1000 check for interrupt after the vCont;c packet, the interrupt character
1001 would stay in the buffer unattended until after the next (unrelated)
1002 stop. */
1003 while (readchar_bufcnt > 0 && *readchar_bufp == '\003')
1005 /* Consume the interrupt character in the buffer. */
1006 readchar ();
1007 the_target->request_interrupt ();
1010 return bp - buf;
1013 void
1014 write_ok (char *buf)
1016 buf[0] = 'O';
1017 buf[1] = 'K';
1018 buf[2] = '\0';
1021 void
1022 write_enn (char *buf)
1024 /* Some day, we should define the meanings of the error codes... */
1025 buf[0] = 'E';
1026 buf[1] = '0';
1027 buf[2] = '1';
1028 buf[3] = '\0';
1031 #endif
1033 #ifndef IN_PROCESS_AGENT
1035 static char *
1036 outreg (struct regcache *regcache, int regno, char *buf)
1038 if ((regno >> 12) != 0)
1039 *buf++ = tohex ((regno >> 12) & 0xf);
1040 if ((regno >> 8) != 0)
1041 *buf++ = tohex ((regno >> 8) & 0xf);
1042 *buf++ = tohex ((regno >> 4) & 0xf);
1043 *buf++ = tohex (regno & 0xf);
1044 *buf++ = ':';
1045 collect_register_as_string (regcache, regno, buf);
1046 buf += 2 * register_size (regcache->tdesc, regno);
1047 *buf++ = ';';
1049 return buf;
1052 void
1053 prepare_resume_reply (char *buf, ptid_t ptid, const target_waitstatus &status)
1055 client_state &cs = get_client_state ();
1056 threads_debug_printf ("Writing resume reply for %s: %s",
1057 target_pid_to_str (ptid).c_str (),
1058 status.to_string ().c_str ());
1060 switch (status.kind ())
1062 case TARGET_WAITKIND_STOPPED:
1063 case TARGET_WAITKIND_FORKED:
1064 case TARGET_WAITKIND_VFORKED:
1065 case TARGET_WAITKIND_VFORK_DONE:
1066 case TARGET_WAITKIND_EXECD:
1067 case TARGET_WAITKIND_THREAD_CREATED:
1068 case TARGET_WAITKIND_SYSCALL_ENTRY:
1069 case TARGET_WAITKIND_SYSCALL_RETURN:
1071 struct regcache *regcache;
1072 char *buf_start = buf;
1074 if ((status.kind () == TARGET_WAITKIND_FORKED && cs.report_fork_events)
1075 || (status.kind () == TARGET_WAITKIND_VFORKED
1076 && cs.report_vfork_events))
1078 enum gdb_signal signal = GDB_SIGNAL_TRAP;
1079 const char *event = (status.kind () == TARGET_WAITKIND_FORKED
1080 ? "fork" : "vfork");
1082 sprintf (buf, "T%02x%s:", signal, event);
1083 buf += strlen (buf);
1084 buf = write_ptid (buf, status.child_ptid ());
1085 strcat (buf, ";");
1087 else if (status.kind () == TARGET_WAITKIND_VFORK_DONE
1088 && cs.report_vfork_events)
1090 enum gdb_signal signal = GDB_SIGNAL_TRAP;
1092 sprintf (buf, "T%02xvforkdone:;", signal);
1094 else if (status.kind () == TARGET_WAITKIND_EXECD && cs.report_exec_events)
1096 enum gdb_signal signal = GDB_SIGNAL_TRAP;
1097 const char *event = "exec";
1098 char hexified_pathname[PATH_MAX * 2];
1100 sprintf (buf, "T%02x%s:", signal, event);
1101 buf += strlen (buf);
1103 /* Encode pathname to hexified format. */
1104 bin2hex ((const gdb_byte *) status.execd_pathname (),
1105 hexified_pathname,
1106 strlen (status.execd_pathname ()));
1108 sprintf (buf, "%s;", hexified_pathname);
1109 buf += strlen (buf);
1111 else if (status.kind () == TARGET_WAITKIND_THREAD_CREATED
1112 && cs.report_thread_events)
1114 enum gdb_signal signal = GDB_SIGNAL_TRAP;
1116 sprintf (buf, "T%02xcreate:;", signal);
1118 else if (status.kind () == TARGET_WAITKIND_SYSCALL_ENTRY
1119 || status.kind () == TARGET_WAITKIND_SYSCALL_RETURN)
1121 enum gdb_signal signal = GDB_SIGNAL_TRAP;
1122 const char *event = (status.kind () == TARGET_WAITKIND_SYSCALL_ENTRY
1123 ? "syscall_entry" : "syscall_return");
1125 sprintf (buf, "T%02x%s:%x;", signal, event,
1126 status.syscall_number ());
1128 else
1129 sprintf (buf, "T%02x", status.sig ());
1131 if (disable_packet_T)
1133 /* This is a bit (OK, a lot) of a kludge, however, this isn't
1134 really a user feature, but exists only so GDB can use the
1135 gdbserver to test handling of the 'S' stop reply packet, so
1136 we would rather this code be as simple as possible.
1138 By this point we've started to build the 'T' stop packet,
1139 and it should look like 'Txx....' where 'x' is a hex digit.
1140 An 'S' stop packet always looks like 'Sxx', so all we do
1141 here is convert the buffer from a T packet to an S packet
1142 and the avoid adding any extra content by breaking out. */
1143 gdb_assert (buf_start[0] == 'T');
1144 gdb_assert (isxdigit (buf_start[1]));
1145 gdb_assert (isxdigit (buf_start[2]));
1146 buf_start[0] = 'S';
1147 buf_start[3] = '\0';
1148 break;
1151 buf += strlen (buf);
1153 scoped_restore_current_thread restore_thread;
1155 switch_to_thread (the_target, ptid);
1157 regcache = get_thread_regcache (current_thread, 1);
1159 if (the_target->stopped_by_watchpoint ())
1161 CORE_ADDR addr;
1162 int i;
1164 memcpy (buf, "watch:", 6);
1165 buf += 6;
1167 addr = the_target->stopped_data_address ();
1169 /* Convert each byte of the address into two hexadecimal
1170 chars. Note that we take sizeof (void *) instead of
1171 sizeof (addr); this is to avoid sending a 64-bit
1172 address to a 32-bit GDB. */
1173 for (i = sizeof (void *) * 2; i > 0; i--)
1174 *buf++ = tohex ((addr >> (i - 1) * 4) & 0xf);
1175 *buf++ = ';';
1177 else if (cs.swbreak_feature && target_stopped_by_sw_breakpoint ())
1179 sprintf (buf, "swbreak:;");
1180 buf += strlen (buf);
1182 else if (cs.hwbreak_feature && target_stopped_by_hw_breakpoint ())
1184 sprintf (buf, "hwbreak:;");
1185 buf += strlen (buf);
1188 /* Handle the expedited registers. */
1189 for (const std::string &expedited_reg :
1190 current_target_desc ()->expedite_regs)
1191 buf = outreg (regcache, find_regno (regcache->tdesc,
1192 expedited_reg.c_str ()), buf);
1193 *buf = '\0';
1195 /* Formerly, if the debugger had not used any thread features
1196 we would not burden it with a thread status response. This
1197 was for the benefit of GDB 4.13 and older. However, in
1198 recent GDB versions the check (``if (cont_thread != 0)'')
1199 does not have the desired effect because of silliness in
1200 the way that the remote protocol handles specifying a
1201 thread. Since thread support relies on qSymbol support
1202 anyway, assume GDB can handle threads. */
1204 if (using_threads && !disable_packet_Tthread)
1206 /* This if (1) ought to be unnecessary. But remote_wait
1207 in GDB will claim this event belongs to inferior_ptid
1208 if we do not specify a thread, and there's no way for
1209 gdbserver to know what inferior_ptid is. */
1210 if (1 || cs.general_thread != ptid)
1212 int core = -1;
1213 /* In non-stop, don't change the general thread behind
1214 GDB's back. */
1215 if (!non_stop)
1216 cs.general_thread = ptid;
1217 sprintf (buf, "thread:");
1218 buf += strlen (buf);
1219 buf = write_ptid (buf, ptid);
1220 strcat (buf, ";");
1221 buf += strlen (buf);
1223 core = target_core_of_thread (ptid);
1225 if (core != -1)
1227 sprintf (buf, "core:");
1228 buf += strlen (buf);
1229 sprintf (buf, "%x", core);
1230 strcat (buf, ";");
1231 buf += strlen (buf);
1236 if (current_process ()->dlls_changed)
1238 strcpy (buf, "library:;");
1239 buf += strlen (buf);
1240 current_process ()->dlls_changed = false;
1243 break;
1244 case TARGET_WAITKIND_EXITED:
1245 if (cs.multi_process)
1246 sprintf (buf, "W%x;process:%x",
1247 status.exit_status (), ptid.pid ());
1248 else
1249 sprintf (buf, "W%02x", status.exit_status ());
1250 break;
1251 case TARGET_WAITKIND_SIGNALLED:
1252 if (cs.multi_process)
1253 sprintf (buf, "X%x;process:%x",
1254 status.sig (), ptid.pid ());
1255 else
1256 sprintf (buf, "X%02x", status.sig ());
1257 break;
1258 case TARGET_WAITKIND_THREAD_EXITED:
1259 sprintf (buf, "w%x;", status.exit_status ());
1260 buf += strlen (buf);
1261 buf = write_ptid (buf, ptid);
1262 break;
1263 case TARGET_WAITKIND_NO_RESUMED:
1264 sprintf (buf, "N");
1265 break;
1266 default:
1267 error ("unhandled waitkind");
1268 break;
1272 /* See remote-utils.h. */
1274 const char *
1275 decode_m_packet_params (const char *from, CORE_ADDR *mem_addr_ptr,
1276 unsigned int *len_ptr, const char end_marker)
1278 int i = 0;
1279 char ch;
1280 *mem_addr_ptr = *len_ptr = 0;
1282 while ((ch = from[i++]) != ',')
1284 *mem_addr_ptr = *mem_addr_ptr << 4;
1285 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1288 while ((ch = from[i++]) != end_marker)
1290 *len_ptr = *len_ptr << 4;
1291 *len_ptr |= fromhex (ch) & 0x0f;
1294 return from + i;
1297 void
1298 decode_m_packet (const char *from, CORE_ADDR *mem_addr_ptr,
1299 unsigned int *len_ptr)
1301 decode_m_packet_params (from, mem_addr_ptr, len_ptr, '\0');
1304 void
1305 decode_M_packet (const char *from, CORE_ADDR *mem_addr_ptr,
1306 unsigned int *len_ptr, unsigned char **to_p)
1308 from = decode_m_packet_params (from, mem_addr_ptr, len_ptr, ':');
1310 if (*to_p == NULL)
1311 *to_p = (unsigned char *) xmalloc (*len_ptr);
1313 hex2bin (from, *to_p, *len_ptr);
1317 decode_X_packet (char *from, int packet_len, CORE_ADDR *mem_addr_ptr,
1318 unsigned int *len_ptr, unsigned char **to_p)
1320 int i = 0;
1321 char ch;
1322 *mem_addr_ptr = *len_ptr = 0;
1324 while ((ch = from[i++]) != ',')
1326 *mem_addr_ptr = *mem_addr_ptr << 4;
1327 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1330 while ((ch = from[i++]) != ':')
1332 *len_ptr = *len_ptr << 4;
1333 *len_ptr |= fromhex (ch) & 0x0f;
1336 if (*to_p == NULL)
1337 *to_p = (unsigned char *) xmalloc (*len_ptr);
1339 if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len - i,
1340 *to_p, *len_ptr) != *len_ptr)
1341 return -1;
1343 return 0;
1346 /* Decode a qXfer write request. */
1349 decode_xfer_write (char *buf, int packet_len, CORE_ADDR *offset,
1350 unsigned int *len, unsigned char *data)
1352 char ch;
1353 char *b = buf;
1355 /* Extract the offset. */
1356 *offset = 0;
1357 while ((ch = *buf++) != ':')
1359 *offset = *offset << 4;
1360 *offset |= fromhex (ch) & 0x0f;
1363 /* Get encoded data. */
1364 packet_len -= buf - b;
1365 *len = remote_unescape_input ((const gdb_byte *) buf, packet_len,
1366 data, packet_len);
1367 return 0;
1370 /* Decode the parameters of a qSearch:memory packet. */
1373 decode_search_memory_packet (const char *buf, int packet_len,
1374 CORE_ADDR *start_addrp,
1375 CORE_ADDR *search_space_lenp,
1376 gdb_byte *pattern, unsigned int *pattern_lenp)
1378 const char *p = buf;
1380 p = decode_address_to_semicolon (start_addrp, p);
1381 p = decode_address_to_semicolon (search_space_lenp, p);
1382 packet_len -= p - buf;
1383 *pattern_lenp = remote_unescape_input ((const gdb_byte *) p, packet_len,
1384 pattern, packet_len);
1385 return 0;
1388 static void
1389 free_sym_cache (struct sym_cache *sym)
1391 if (sym != NULL)
1393 free (sym->name);
1394 free (sym);
1398 void
1399 clear_symbol_cache (struct sym_cache **symcache_p)
1401 struct sym_cache *sym, *next;
1403 /* Check the cache first. */
1404 for (sym = *symcache_p; sym; sym = next)
1406 next = sym->next;
1407 free_sym_cache (sym);
1410 *symcache_p = NULL;
1413 /* Get the address of NAME, and return it in ADDRP if found. if
1414 MAY_ASK_GDB is false, assume symbol cache misses are failures.
1415 Returns 1 if the symbol is found, 0 if it is not, -1 on error. */
1418 look_up_one_symbol (const char *name, CORE_ADDR *addrp, int may_ask_gdb)
1420 client_state &cs = get_client_state ();
1421 char *p, *q;
1422 int len;
1423 struct sym_cache *sym;
1424 struct process_info *proc;
1426 proc = current_process ();
1428 /* Check the cache first. */
1429 for (sym = proc->symbol_cache; sym; sym = sym->next)
1430 if (strcmp (name, sym->name) == 0)
1432 *addrp = sym->addr;
1433 return 1;
1436 /* It might not be an appropriate time to look up a symbol,
1437 e.g. while we're trying to fetch registers. */
1438 if (!may_ask_gdb)
1439 return 0;
1441 /* Send the request. */
1442 strcpy (cs.own_buf, "qSymbol:");
1443 bin2hex ((const gdb_byte *) name, cs.own_buf + strlen ("qSymbol:"),
1444 strlen (name));
1445 if (putpkt (cs.own_buf) < 0)
1446 return -1;
1448 /* FIXME: Eventually add buffer overflow checking (to getpkt?) */
1449 len = getpkt (cs.own_buf);
1450 if (len < 0)
1451 return -1;
1453 /* We ought to handle pretty much any packet at this point while we
1454 wait for the qSymbol "response". That requires re-entering the
1455 main loop. For now, this is an adequate approximation; allow
1456 GDB to read from memory and handle 'v' packets (for vFile transfers)
1457 while it figures out the address of the symbol. */
1458 while (1)
1460 if (cs.own_buf[0] == 'm')
1462 CORE_ADDR mem_addr;
1463 unsigned char *mem_buf;
1464 unsigned int mem_len;
1466 decode_m_packet (&cs.own_buf[1], &mem_addr, &mem_len);
1467 mem_buf = (unsigned char *) xmalloc (mem_len);
1468 if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
1469 bin2hex (mem_buf, cs.own_buf, mem_len);
1470 else
1471 write_enn (cs.own_buf);
1472 free (mem_buf);
1473 if (putpkt (cs.own_buf) < 0)
1474 return -1;
1476 else if (cs.own_buf[0] == 'v')
1478 int new_len = -1;
1479 handle_v_requests (cs.own_buf, len, &new_len);
1480 if (new_len != -1)
1481 putpkt_binary (cs.own_buf, new_len);
1482 else
1483 putpkt (cs.own_buf);
1485 else
1486 break;
1487 len = getpkt (cs.own_buf);
1488 if (len < 0)
1489 return -1;
1492 if (!startswith (cs.own_buf, "qSymbol:"))
1494 warning ("Malformed response to qSymbol, ignoring: %s", cs.own_buf);
1495 return -1;
1498 p = cs.own_buf + strlen ("qSymbol:");
1499 q = p;
1500 while (*q && *q != ':')
1501 q++;
1503 /* Make sure we found a value for the symbol. */
1504 if (p == q || *q == '\0')
1505 return 0;
1507 decode_address (addrp, p, q - p);
1509 /* Save the symbol in our cache. */
1510 sym = XNEW (struct sym_cache);
1511 sym->name = xstrdup (name);
1512 sym->addr = *addrp;
1513 sym->next = proc->symbol_cache;
1514 proc->symbol_cache = sym;
1516 return 1;
1519 /* Relocate an instruction to execute at a different address. OLDLOC
1520 is the address in the inferior memory where the instruction to
1521 relocate is currently at. On input, TO points to the destination
1522 where we want the instruction to be copied (and possibly adjusted)
1523 to. On output, it points to one past the end of the resulting
1524 instruction(s). The effect of executing the instruction at TO
1525 shall be the same as if executing it at OLDLOC. For example, call
1526 instructions that implicitly push the return address on the stack
1527 should be adjusted to return to the instruction after OLDLOC;
1528 relative branches, and other PC-relative instructions need the
1529 offset adjusted; etc. Returns 0 on success, -1 on failure. */
1532 relocate_instruction (CORE_ADDR *to, CORE_ADDR oldloc)
1534 client_state &cs = get_client_state ();
1535 int len;
1536 ULONGEST written = 0;
1538 /* Send the request. */
1539 sprintf (cs.own_buf, "qRelocInsn:%s;%s", paddress (oldloc),
1540 paddress (*to));
1541 if (putpkt (cs.own_buf) < 0)
1542 return -1;
1544 /* FIXME: Eventually add buffer overflow checking (to getpkt?) */
1545 len = getpkt (cs.own_buf);
1546 if (len < 0)
1547 return -1;
1549 /* We ought to handle pretty much any packet at this point while we
1550 wait for the qRelocInsn "response". That requires re-entering
1551 the main loop. For now, this is an adequate approximation; allow
1552 GDB to access memory. */
1553 while (cs.own_buf[0] == 'm' || cs.own_buf[0] == 'M' || cs.own_buf[0] == 'X')
1555 CORE_ADDR mem_addr;
1556 unsigned char *mem_buf = NULL;
1557 unsigned int mem_len;
1559 if (cs.own_buf[0] == 'm')
1561 decode_m_packet (&cs.own_buf[1], &mem_addr, &mem_len);
1562 mem_buf = (unsigned char *) xmalloc (mem_len);
1563 if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
1564 bin2hex (mem_buf, cs.own_buf, mem_len);
1565 else
1566 write_enn (cs.own_buf);
1568 else if (cs.own_buf[0] == 'X')
1570 if (decode_X_packet (&cs.own_buf[1], len - 1, &mem_addr,
1571 &mem_len, &mem_buf) < 0
1572 || target_write_memory (mem_addr, mem_buf, mem_len) != 0)
1573 write_enn (cs.own_buf);
1574 else
1575 write_ok (cs.own_buf);
1577 else
1579 decode_M_packet (&cs.own_buf[1], &mem_addr, &mem_len, &mem_buf);
1580 if (target_write_memory (mem_addr, mem_buf, mem_len) == 0)
1581 write_ok (cs.own_buf);
1582 else
1583 write_enn (cs.own_buf);
1585 free (mem_buf);
1586 if (putpkt (cs.own_buf) < 0)
1587 return -1;
1588 len = getpkt (cs.own_buf);
1589 if (len < 0)
1590 return -1;
1593 if (cs.own_buf[0] == 'E')
1595 warning ("An error occurred while relocating an instruction: %s",
1596 cs.own_buf);
1597 return -1;
1600 if (!startswith (cs.own_buf, "qRelocInsn:"))
1602 warning ("Malformed response to qRelocInsn, ignoring: %s",
1603 cs.own_buf);
1604 return -1;
1607 unpack_varlen_hex (cs.own_buf + strlen ("qRelocInsn:"), &written);
1609 *to += written;
1610 return 0;
1613 void
1614 monitor_output (const char *msg)
1616 int len = strlen (msg);
1617 char *buf = (char *) xmalloc (len * 2 + 2);
1619 buf[0] = 'O';
1620 bin2hex ((const gdb_byte *) msg, buf + 1, len);
1622 putpkt (buf);
1623 free (buf);
1626 #endif