1 /* Remote utility routines for the remote server for GDB.
2 Copyright (C) 1986, 1989, 1993-2012 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/>. */
25 #include <sys/ioctl.h>
31 #include <netinet/in.h>
34 #include <sys/socket.h>
39 #if HAVE_NETINET_TCP_H
40 #include <netinet/tcp.h>
43 #include <sys/ioctl.h>
56 #include <arpa/inet.h>
68 #include <sys/iomgr.h>
71 #ifndef HAVE_SOCKLEN_T
72 typedef int socklen_t;
75 #ifndef IN_PROCESS_AGENT
78 # define INVALID_DESCRIPTOR INVALID_SOCKET
80 # define INVALID_DESCRIPTOR -1
83 /* Extra value for readchar_callback. */
85 /* The callback is currently not scheduled. */
89 /* Status of the readchar callback.
90 Either NOT_SCHEDULED or the callback id. */
91 static int readchar_callback = NOT_SCHEDULED;
93 static int readchar (void);
94 static void reset_readchar (void);
95 static void reschedule (void);
97 /* A cache entry for a successfully looked-up symbol. */
102 struct sym_cache *next;
105 int remote_debug = 0;
106 struct ui_file *gdb_stdlog;
108 static int remote_is_stdio = 0;
110 static gdb_fildes_t remote_desc = INVALID_DESCRIPTOR;
111 static gdb_fildes_t listen_desc = INVALID_DESCRIPTOR;
113 /* FIXME headerize? */
114 extern int using_threads;
115 extern int debug_threads;
117 /* If true, then GDB has requested noack mode. */
119 /* If true, then we tell GDB to use noack mode by default. */
120 int transport_is_reliable = 0;
123 # define read(fd, buf, len) recv (fd, (char *) buf, len, 0)
124 # define write(fd, buf, len) send (fd, (char *) buf, len, 0)
130 return remote_desc != INVALID_DESCRIPTOR;
133 /* Return true if the remote connection is over stdio. */
136 remote_connection_is_stdio (void)
138 return remote_is_stdio;
142 enable_async_notification (int fd)
144 #if defined(F_SETFL) && defined (FASYNC)
145 int save_fcntl_flags;
147 save_fcntl_flags = fcntl (fd, F_GETFL, 0);
148 fcntl (fd, F_SETFL, save_fcntl_flags | FASYNC);
149 #if defined (F_SETOWN)
150 fcntl (fd, F_SETOWN, getpid ());
156 handle_accept_event (int err, gdb_client_data client_data)
158 struct sockaddr_in sockaddr;
162 fprintf (stderr, "handling possible accept event\n");
164 tmp = sizeof (sockaddr);
165 remote_desc = accept (listen_desc, (struct sockaddr *) &sockaddr, &tmp);
166 if (remote_desc == -1)
167 perror_with_name ("Accept failed");
169 /* Enable TCP keep alive process. */
171 setsockopt (remote_desc, SOL_SOCKET, SO_KEEPALIVE,
172 (char *) &tmp, sizeof (tmp));
174 /* Tell TCP not to delay small packets. This greatly speeds up
175 interactive response. */
177 setsockopt (remote_desc, IPPROTO_TCP, TCP_NODELAY,
178 (char *) &tmp, sizeof (tmp));
181 signal (SIGPIPE, SIG_IGN); /* If we don't do this, then gdbserver simply
182 exits when the remote side dies. */
188 close (listen_desc); /* No longer need this */
190 closesocket (listen_desc); /* No longer need this */
194 /* Even if !RUN_ONCE no longer notice new connections. Still keep the
195 descriptor open for add_file_handler to wait for a new connection. */
196 delete_file_handler (listen_desc);
198 /* Convert IP address to string. */
199 fprintf (stderr, "Remote debugging from host %s\n",
200 inet_ntoa (sockaddr.sin_addr));
202 enable_async_notification (remote_desc);
204 /* Register the event loop handler. */
205 add_file_handler (remote_desc, handle_serial_event, NULL);
207 /* We have a new GDB connection now. If we were disconnected
208 tracing, there's a window where the target could report a stop
209 event to the event loop, and since we have a connection now, we'd
210 try to send vStopped notifications to GDB. But, don't do that
211 until GDB as selected all-stop/non-stop, and has queried the
212 threads' status ('?'). */
218 /* Prepare for a later connection to a remote debugger.
219 NAME is the filename used for communication. */
222 remote_prepare (char *name)
226 static int winsock_initialized;
229 struct sockaddr_in sockaddr;
234 if (strcmp (name, STDIO_CONNECTION_NAME) == 0)
236 /* We need to record fact that we're using stdio sooner than the
237 call to remote_open so start_inferior knows the connection is
240 transport_is_reliable = 1;
244 port_str = strchr (name, ':');
245 if (port_str == NULL)
247 transport_is_reliable = 0;
251 port = strtoul (port_str + 1, &port_end, 10);
252 if (port_str[1] == '\0' || *port_end != '\0')
253 fatal ("Bad port argument: %s", name);
256 if (!winsock_initialized)
260 WSAStartup (MAKEWORD (1, 0), &wsad);
261 winsock_initialized = 1;
265 listen_desc = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
266 if (listen_desc == -1)
267 perror_with_name ("Can't open socket");
269 /* Allow rapid reuse of this port. */
271 setsockopt (listen_desc, SOL_SOCKET, SO_REUSEADDR, (char *) &tmp,
274 sockaddr.sin_family = PF_INET;
275 sockaddr.sin_port = htons (port);
276 sockaddr.sin_addr.s_addr = INADDR_ANY;
278 if (bind (listen_desc, (struct sockaddr *) &sockaddr, sizeof (sockaddr))
279 || listen (listen_desc, 1))
280 perror_with_name ("Can't bind address");
282 transport_is_reliable = 1;
285 /* Open a connection to a remote debugger.
286 NAME is the filename used for communication. */
289 remote_open (char *name)
293 port_str = strchr (name, ':');
295 if (port_str == NULL)
296 error ("Only <host>:<port> is supported on this platform.");
299 if (strcmp (name, STDIO_CONNECTION_NAME) == 0)
301 fprintf (stderr, "Remote debugging using stdio\n");
303 /* Use stdin as the handle of the connection.
304 We only select on reads, for example. */
305 remote_desc = fileno (stdin);
307 enable_async_notification (remote_desc);
309 /* Register the event loop handler. */
310 add_file_handler (remote_desc, handle_serial_event, NULL);
313 else if (port_str == NULL)
317 if (stat (name, &statbuf) == 0
318 && (S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode)))
319 remote_desc = open (name, O_RDWR);
327 perror_with_name ("Could not open remote device");
331 struct termios termios;
332 tcgetattr (remote_desc, &termios);
337 termios.c_cflag &= ~(CSIZE | PARENB);
338 termios.c_cflag |= CLOCAL | CS8;
339 termios.c_cc[VMIN] = 1;
340 termios.c_cc[VTIME] = 0;
342 tcsetattr (remote_desc, TCSANOW, &termios);
348 struct termio termio;
349 ioctl (remote_desc, TCGETA, &termio);
354 termio.c_cflag &= ~(CSIZE | PARENB);
355 termio.c_cflag |= CLOCAL | CS8;
356 termio.c_cc[VMIN] = 1;
357 termio.c_cc[VTIME] = 0;
359 ioctl (remote_desc, TCSETA, &termio);
367 ioctl (remote_desc, TIOCGETP, &sg);
369 ioctl (remote_desc, TIOCSETP, &sg);
373 fprintf (stderr, "Remote debugging using %s\n", name);
375 enable_async_notification (remote_desc);
377 /* Register the event loop handler. */
378 add_file_handler (remote_desc, handle_serial_event, NULL);
380 #endif /* USE_WIN32API */
385 struct sockaddr_in sockaddr;
387 len = sizeof (sockaddr);
388 if (getsockname (listen_desc,
389 (struct sockaddr *) &sockaddr, &len) < 0
390 || len < sizeof (sockaddr))
391 perror_with_name ("Can't determine port");
392 port = ntohs (sockaddr.sin_port);
394 fprintf (stderr, "Listening on port %d\n", port);
397 /* Register the event loop handler. */
398 add_file_handler (listen_desc, handle_accept_event, NULL);
405 delete_file_handler (remote_desc);
408 closesocket (remote_desc);
410 if (! remote_connection_is_stdio ())
413 remote_desc = INVALID_DESCRIPTOR;
418 /* Convert hex digit A to a number. */
423 if (a >= '0' && a <= '9')
425 else if (a >= 'a' && a <= 'f')
428 error ("Reply contains invalid hex digit");
434 static const char hexchars[] = "0123456789abcdef";
437 ishex (int ch, int *val)
439 if ((ch >= 'a') && (ch <= 'f'))
441 *val = ch - 'a' + 10;
444 if ((ch >= 'A') && (ch <= 'F'))
446 *val = ch - 'A' + 10;
449 if ((ch >= '0') && (ch <= '9'))
457 #ifndef IN_PROCESS_AGENT
460 unhexify (char *bin, const char *hex, int count)
464 for (i = 0; i < count; i++)
466 if (hex[0] == 0 || hex[1] == 0)
468 /* Hex string is short, or of uneven length.
469 Return the count that has been converted so far. */
472 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
479 decode_address (CORE_ADDR *addrp, const char *start, int len)
486 for (i = 0; i < len; i++)
490 addr = addr | (fromhex (ch) & 0x0f);
496 decode_address_to_semicolon (CORE_ADDR *addrp, const char *start)
501 while (*end != '\0' && *end != ';')
504 decode_address (addrp, start, end - start);
513 /* Convert number NIB to a hex digit. */
521 return 'a' + nib - 10;
524 #ifndef IN_PROCESS_AGENT
527 hexify (char *hex, const char *bin, int count)
531 /* May use a length, or a nul-terminated string as input. */
533 count = strlen (bin);
535 for (i = 0; i < count; i++)
537 *hex++ = tohex ((*bin >> 4) & 0xf);
538 *hex++ = tohex (*bin++ & 0xf);
544 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
545 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
546 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
547 (which may be more than *OUT_LEN due to escape characters). The
548 total number of bytes in the output buffer will be at most
552 remote_escape_output (const gdb_byte *buffer, int len,
553 gdb_byte *out_buf, int *out_len,
556 int input_index, output_index;
559 for (input_index = 0; input_index < len; input_index++)
561 gdb_byte b = buffer[input_index];
563 if (b == '$' || b == '#' || b == '}' || b == '*')
565 /* These must be escaped. */
566 if (output_index + 2 > out_maxlen)
568 out_buf[output_index++] = '}';
569 out_buf[output_index++] = b ^ 0x20;
573 if (output_index + 1 > out_maxlen)
575 out_buf[output_index++] = b;
579 *out_len = input_index;
583 /* Convert BUFFER, escaped data LEN bytes long, into binary data
584 in OUT_BUF. Return the number of bytes written to OUT_BUF.
585 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
587 This function reverses remote_escape_output. It allows more
588 escaped characters than that function does, in particular because
589 '*' must be escaped to avoid the run-length encoding processing
590 in reading packets. */
593 remote_unescape_input (const gdb_byte *buffer, int len,
594 gdb_byte *out_buf, int out_maxlen)
596 int input_index, output_index;
601 for (input_index = 0; input_index < len; input_index++)
603 gdb_byte b = buffer[input_index];
605 if (output_index + 1 > out_maxlen)
606 error ("Received too much data from the target.");
610 out_buf[output_index++] = b ^ 0x20;
616 out_buf[output_index++] = b;
620 error ("Unmatched escape character in target response.");
625 /* Look for a sequence of characters which can be run-length encoded.
626 If there are any, update *CSUM and *P. Otherwise, output the
627 single character. Return the number of characters consumed. */
630 try_rle (char *buf, int remaining, unsigned char *csum, char **p)
634 /* Always output the character. */
638 /* Don't go past '~'. */
642 for (n = 1; n < remaining; n++)
643 if (buf[n] != buf[0])
646 /* N is the index of the first character not the same as buf[0].
647 buf[0] is counted twice, so by decrementing N, we get the number
648 of characters the RLE sequence will replace. */
654 /* Skip the frame characters. The manual says to skip '+' and '-'
655 also, but there's no reason to. Unfortunately these two unusable
656 characters double the encoded length of a four byte zero
658 while (n + 29 == '$' || n + 29 == '#')
672 unpack_varlen_hex (char *buff, /* packet to parse */
678 while (ishex (*buff, &nibble))
681 retval = retval << 4;
682 retval |= nibble & 0x0f;
688 #ifndef IN_PROCESS_AGENT
690 /* Write a PTID to BUF. Returns BUF+CHARACTERS_WRITTEN. */
693 write_ptid (char *buf, ptid_t ptid)
699 pid = ptid_get_pid (ptid);
701 buf += sprintf (buf, "p-%x.", -pid);
703 buf += sprintf (buf, "p%x.", pid);
705 tid = ptid_get_lwp (ptid);
707 buf += sprintf (buf, "-%x", -tid);
709 buf += sprintf (buf, "%x", tid);
715 hex_or_minus_one (char *buf, char **obuf)
719 if (strncmp (buf, "-1", 2) == 0)
725 buf = unpack_varlen_hex (buf, &ret);
733 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
734 passed the last parsed char. Returns null_ptid on error. */
736 read_ptid (char *buf, char **obuf)
740 ULONGEST pid = 0, tid = 0;
744 /* Multi-process ptid. */
745 pp = unpack_varlen_hex (p + 1, &pid);
747 error ("invalid remote ptid: %s\n", p);
751 tid = hex_or_minus_one (p, &pp);
755 return ptid_build (pid, tid, 0);
758 /* No multi-process. Just a tid. */
759 tid = hex_or_minus_one (p, &pp);
761 /* Since the stub is not sending a process id, then default to
762 what's in the current inferior. */
763 pid = ptid_get_pid (((struct inferior_list_entry *) current_inferior)->id);
767 return ptid_build (pid, tid, 0);
770 /* Write COUNT bytes in BUF to the client.
771 The result is the number of bytes written or -1 if error.
772 This may return less than COUNT. */
775 write_prim (const void *buf, int count)
777 if (remote_connection_is_stdio ())
778 return write (fileno (stdout), buf, count);
780 return write (remote_desc, buf, count);
783 /* Read COUNT bytes from the client and store in BUF.
784 The result is the number of bytes read or -1 if error.
785 This may return less than COUNT. */
788 read_prim (void *buf, int count)
790 if (remote_connection_is_stdio ())
791 return read (fileno (stdin), buf, count);
793 return read (remote_desc, buf, count);
796 /* Send a packet to the remote machine, with error checking.
797 The data of the packet is in BUF, and the length of the
798 packet is in CNT. Returns >= 0 on success, -1 otherwise. */
801 putpkt_binary_1 (char *buf, int cnt, int is_notif)
804 unsigned char csum = 0;
809 buf2 = xmalloc (strlen ("$") + cnt + strlen ("#nn") + 1);
811 /* Copy the packet into buffer BUF2, encapsulating it
812 and giving it a checksum. */
820 for (i = 0; i < cnt;)
821 i += try_rle (buf + i, cnt - i, &csum, &p);
824 *p++ = tohex ((csum >> 4) & 0xf);
825 *p++ = tohex (csum & 0xf);
829 /* Send it over and over until we get a positive ack. */
833 if (write_prim (buf2, p - buf2) != p - buf2)
835 perror ("putpkt(write)");
840 if (noack_mode || is_notif)
842 /* Don't expect an ack then. */
846 fprintf (stderr, "putpkt (\"%s\"); [notif]\n", buf2);
848 fprintf (stderr, "putpkt (\"%s\"); [noack mode]\n", buf2);
856 fprintf (stderr, "putpkt (\"%s\"); [looking for ack]\n", buf2);
870 fprintf (stderr, "[received '%c' (0x%x)]\n", cc, cc);
874 /* Check for an input interrupt while we're here. */
875 if (cc == '\003' && current_inferior != NULL)
876 (*the_target->request_interrupt) ();
881 return 1; /* Success! */
885 putpkt_binary (char *buf, int cnt)
887 return putpkt_binary_1 (buf, cnt, 0);
890 /* Send a packet to the remote machine, with error checking. The data
891 of the packet is in BUF, and the packet should be a NUL-terminated
892 string. Returns >= 0 on success, -1 otherwise. */
897 return putpkt_binary (buf, strlen (buf));
901 putpkt_notif (char *buf)
903 return putpkt_binary_1 (buf, strlen (buf), 1);
906 /* Come here when we get an input interrupt from the remote side. This
907 interrupt should only be active while we are waiting for the child to do
908 something. Thus this assumes readchar:bufcnt is 0.
909 About the only thing that should come through is a ^C, which
910 will cause us to request child interruption. */
913 input_interrupt (int unused)
916 struct timeval immediate = { 0, 0 };
918 /* Protect against spurious interrupts. This has been observed to
919 be a problem under NetBSD 1.4 and 1.5. */
922 FD_SET (remote_desc, &readset);
923 if (select (remote_desc + 1, &readset, 0, 0, &immediate) > 0)
928 cc = read_prim (&c, 1);
930 if (cc != 1 || c != '\003' || current_inferior == NULL)
932 fprintf (stderr, "input_interrupt, count = %d c = %d ('%c')\n",
937 (*the_target->request_interrupt) ();
941 /* Check if the remote side sent us an interrupt request (^C). */
943 check_remote_input_interrupt_request (void)
945 /* This function may be called before establishing communications,
946 therefore we need to validate the remote descriptor. */
948 if (remote_desc == INVALID_DESCRIPTOR)
954 /* Asynchronous I/O support. SIGIO must be enabled when waiting, in order to
955 accept Control-C from the client, and must be disabled when talking to
959 unblock_async_io (void)
964 sigemptyset (&sigio_set);
965 sigaddset (&sigio_set, SIGIO);
966 sigprocmask (SIG_UNBLOCK, &sigio_set, NULL);
972 nto_comctrl (int enable)
974 struct sigevent event;
978 event.sigev_notify = SIGEV_SIGNAL_THREAD;
979 event.sigev_signo = SIGIO;
980 event.sigev_code = 0;
981 event.sigev_value.sival_ptr = NULL;
982 event.sigev_priority = -1;
983 ionotify (remote_desc, _NOTIFY_ACTION_POLLARM, _NOTIFY_COND_INPUT,
987 ionotify (remote_desc, _NOTIFY_ACTION_POLL, _NOTIFY_COND_INPUT, NULL);
992 /* Current state of asynchronous I/O. */
993 static int async_io_enabled;
995 /* Enable asynchronous I/O. */
997 enable_async_io (void)
999 if (async_io_enabled)
1002 #ifndef USE_WIN32API
1003 signal (SIGIO, input_interrupt);
1005 async_io_enabled = 1;
1008 #endif /* __QNX__ */
1011 /* Disable asynchronous I/O. */
1013 disable_async_io (void)
1015 if (!async_io_enabled)
1018 #ifndef USE_WIN32API
1019 signal (SIGIO, SIG_IGN);
1021 async_io_enabled = 0;
1024 #endif /* __QNX__ */
1029 initialize_async_io (void)
1031 /* Make sure that async I/O starts disabled. */
1032 async_io_enabled = 1;
1033 disable_async_io ();
1035 /* Make sure the signal is unblocked. */
1036 unblock_async_io ();
1039 /* Internal buffer used by readchar.
1040 These are global to readchar because reschedule_remote needs to be
1041 able to tell whether the buffer is empty. */
1043 static unsigned char readchar_buf[BUFSIZ];
1044 static int readchar_bufcnt = 0;
1045 static unsigned char *readchar_bufp;
1047 /* Returns next char from remote GDB. -1 if error. */
1054 if (readchar_bufcnt == 0)
1056 readchar_bufcnt = read_prim (readchar_buf, sizeof (readchar_buf));
1058 if (readchar_bufcnt <= 0)
1060 if (readchar_bufcnt == 0)
1061 fprintf (stderr, "readchar: Got EOF\n");
1063 perror ("readchar");
1068 readchar_bufp = readchar_buf;
1072 ch = *readchar_bufp++;
1077 /* Reset the readchar state machine. */
1080 reset_readchar (void)
1082 readchar_bufcnt = 0;
1083 if (readchar_callback != NOT_SCHEDULED)
1085 delete_callback_event (readchar_callback);
1086 readchar_callback = NOT_SCHEDULED;
1090 /* Process remaining data in readchar_buf. */
1093 process_remaining (void *context)
1097 /* This is a one-shot event. */
1098 readchar_callback = NOT_SCHEDULED;
1100 if (readchar_bufcnt > 0)
1101 res = handle_serial_event (0, NULL);
1108 /* If there is still data in the buffer, queue another event to process it,
1109 we can't sleep in select yet. */
1114 if (readchar_bufcnt > 0 && readchar_callback == NOT_SCHEDULED)
1115 readchar_callback = append_callback_event (process_remaining, NULL);
1118 /* Read a packet from the remote machine, with error checking,
1119 and store it in BUF. Returns length of packet, or negative if error. */
1125 unsigned char csum, c1, c2;
1139 fprintf (stderr, "[getpkt: discarding char '%c']\n", c);
1160 c1 = fromhex (readchar ());
1161 c2 = fromhex (readchar ());
1163 if (csum == (c1 << 4) + c2)
1169 "Bad checksum, sentsum=0x%x, csum=0x%x, "
1170 "buf=%s [no-ack-mode, Bad medium?]\n",
1171 (c1 << 4) + c2, csum, buf);
1172 /* Not much we can do, GDB wasn't expecting an ack/nac. */
1176 fprintf (stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
1177 (c1 << 4) + c2, csum, buf);
1178 if (write_prim ("-", 1) != 1)
1186 fprintf (stderr, "getpkt (\"%s\"); [sending ack] \n", buf);
1190 if (write_prim ("+", 1) != 1)
1195 fprintf (stderr, "[sent ack]\n");
1203 fprintf (stderr, "getpkt (\"%s\"); [no ack sent] \n", buf);
1212 write_ok (char *buf)
1220 write_enn (char *buf)
1222 /* Some day, we should define the meanings of the error codes... */
1232 convert_int_to_ascii (const unsigned char *from, char *to, int n)
1239 nib = ((ch & 0xf0) >> 4) & 0x0f;
1240 *to++ = tohex (nib);
1242 *to++ = tohex (nib);
1247 #ifndef IN_PROCESS_AGENT
1250 convert_ascii_to_int (const char *from, unsigned char *to, int n)
1255 nib1 = fromhex (*from++);
1256 nib2 = fromhex (*from++);
1257 *to++ = (((nib1 & 0x0f) << 4) & 0xf0) | (nib2 & 0x0f);
1262 outreg (struct regcache *regcache, int regno, char *buf)
1264 if ((regno >> 12) != 0)
1265 *buf++ = tohex ((regno >> 12) & 0xf);
1266 if ((regno >> 8) != 0)
1267 *buf++ = tohex ((regno >> 8) & 0xf);
1268 *buf++ = tohex ((regno >> 4) & 0xf);
1269 *buf++ = tohex (regno & 0xf);
1271 collect_register_as_string (regcache, regno, buf);
1272 buf += 2 * register_size (regno);
1279 new_thread_notify (int id)
1283 /* The `n' response is not yet part of the remote protocol. Do nothing. */
1287 if (server_waiting == 0)
1290 sprintf (own_buf, "n%x", id);
1291 disable_async_io ();
1297 dead_thread_notify (int id)
1301 /* The `x' response is not yet part of the remote protocol. Do nothing. */
1305 sprintf (own_buf, "x%x", id);
1306 disable_async_io ();
1312 prepare_resume_reply (char *buf, ptid_t ptid,
1313 struct target_waitstatus *status)
1316 fprintf (stderr, "Writing resume reply for %s:%d\n",
1317 target_pid_to_str (ptid), status->kind);
1319 switch (status->kind)
1321 case TARGET_WAITKIND_STOPPED:
1323 struct thread_info *saved_inferior;
1325 struct regcache *regcache;
1327 sprintf (buf, "T%02x", status->value.sig);
1328 buf += strlen (buf);
1330 regp = gdbserver_expedite_regs;
1332 saved_inferior = current_inferior;
1334 current_inferior = find_thread_ptid (ptid);
1336 regcache = get_thread_regcache (current_inferior, 1);
1338 if (the_target->stopped_by_watchpoint != NULL
1339 && (*the_target->stopped_by_watchpoint) ())
1344 strncpy (buf, "watch:", 6);
1347 addr = (*the_target->stopped_data_address) ();
1349 /* Convert each byte of the address into two hexadecimal
1350 chars. Note that we take sizeof (void *) instead of
1351 sizeof (addr); this is to avoid sending a 64-bit
1352 address to a 32-bit GDB. */
1353 for (i = sizeof (void *) * 2; i > 0; i--)
1354 *buf++ = tohex ((addr >> (i - 1) * 4) & 0xf);
1360 buf = outreg (regcache, find_regno (*regp), buf);
1365 /* Formerly, if the debugger had not used any thread features
1366 we would not burden it with a thread status response. This
1367 was for the benefit of GDB 4.13 and older. However, in
1368 recent GDB versions the check (``if (cont_thread != 0)'')
1369 does not have the desired effect because of sillyness in
1370 the way that the remote protocol handles specifying a
1371 thread. Since thread support relies on qSymbol support
1372 anyway, assume GDB can handle threads. */
1374 if (using_threads && !disable_packet_Tthread)
1376 /* This if (1) ought to be unnecessary. But remote_wait
1377 in GDB will claim this event belongs to inferior_ptid
1378 if we do not specify a thread, and there's no way for
1379 gdbserver to know what inferior_ptid is. */
1380 if (1 || !ptid_equal (general_thread, ptid))
1383 /* In non-stop, don't change the general thread behind
1386 general_thread = ptid;
1387 sprintf (buf, "thread:");
1388 buf += strlen (buf);
1389 buf = write_ptid (buf, ptid);
1391 buf += strlen (buf);
1393 core = target_core_of_thread (ptid);
1397 sprintf (buf, "core:");
1398 buf += strlen (buf);
1399 sprintf (buf, "%x", core);
1401 buf += strlen (buf);
1408 strcpy (buf, "library:;");
1409 buf += strlen (buf);
1413 current_inferior = saved_inferior;
1416 case TARGET_WAITKIND_EXITED:
1418 sprintf (buf, "W%x;process:%x",
1419 status->value.integer, ptid_get_pid (ptid));
1421 sprintf (buf, "W%02x", status->value.integer);
1423 case TARGET_WAITKIND_SIGNALLED:
1425 sprintf (buf, "X%x;process:%x",
1426 status->value.sig, ptid_get_pid (ptid));
1428 sprintf (buf, "X%02x", status->value.sig);
1431 error ("unhandled waitkind");
1437 decode_m_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr)
1441 *mem_addr_ptr = *len_ptr = 0;
1443 while ((ch = from[i++]) != ',')
1445 *mem_addr_ptr = *mem_addr_ptr << 4;
1446 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1449 for (j = 0; j < 4; j++)
1451 if ((ch = from[i++]) == 0)
1453 *len_ptr = *len_ptr << 4;
1454 *len_ptr |= fromhex (ch) & 0x0f;
1459 decode_M_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr,
1460 unsigned char **to_p)
1464 *mem_addr_ptr = *len_ptr = 0;
1466 while ((ch = from[i++]) != ',')
1468 *mem_addr_ptr = *mem_addr_ptr << 4;
1469 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1472 while ((ch = from[i++]) != ':')
1474 *len_ptr = *len_ptr << 4;
1475 *len_ptr |= fromhex (ch) & 0x0f;
1479 *to_p = xmalloc (*len_ptr);
1481 convert_ascii_to_int (&from[i++], *to_p, *len_ptr);
1485 decode_X_packet (char *from, int packet_len, CORE_ADDR *mem_addr_ptr,
1486 unsigned int *len_ptr, unsigned char **to_p)
1490 *mem_addr_ptr = *len_ptr = 0;
1492 while ((ch = from[i++]) != ',')
1494 *mem_addr_ptr = *mem_addr_ptr << 4;
1495 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1498 while ((ch = from[i++]) != ':')
1500 *len_ptr = *len_ptr << 4;
1501 *len_ptr |= fromhex (ch) & 0x0f;
1505 *to_p = xmalloc (*len_ptr);
1507 if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len - i,
1508 *to_p, *len_ptr) != *len_ptr)
1514 /* Decode a qXfer write request. */
1517 decode_xfer_write (char *buf, int packet_len, CORE_ADDR *offset,
1518 unsigned int *len, unsigned char *data)
1523 /* Extract the offset. */
1525 while ((ch = *buf++) != ':')
1527 *offset = *offset << 4;
1528 *offset |= fromhex (ch) & 0x0f;
1531 /* Get encoded data. */
1532 packet_len -= buf - b;
1533 *len = remote_unescape_input ((const gdb_byte *) buf, packet_len,
1538 /* Decode the parameters of a qSearch:memory packet. */
1541 decode_search_memory_packet (const char *buf, int packet_len,
1542 CORE_ADDR *start_addrp,
1543 CORE_ADDR *search_space_lenp,
1544 gdb_byte *pattern, unsigned int *pattern_lenp)
1546 const char *p = buf;
1548 p = decode_address_to_semicolon (start_addrp, p);
1549 p = decode_address_to_semicolon (search_space_lenp, p);
1550 packet_len -= p - buf;
1551 *pattern_lenp = remote_unescape_input ((const gdb_byte *) p, packet_len,
1552 pattern, packet_len);
1557 free_sym_cache (struct sym_cache *sym)
1567 clear_symbol_cache (struct sym_cache **symcache_p)
1569 struct sym_cache *sym, *next;
1571 /* Check the cache first. */
1572 for (sym = *symcache_p; sym; sym = next)
1575 free_sym_cache (sym);
1581 /* Get the address of NAME, and return it in ADDRP if found. if
1582 MAY_ASK_GDB is false, assume symbol cache misses are failures.
1583 Returns 1 if the symbol is found, 0 if it is not, -1 on error. */
1586 look_up_one_symbol (const char *name, CORE_ADDR *addrp, int may_ask_gdb)
1588 char own_buf[266], *p, *q;
1590 struct sym_cache *sym;
1591 struct process_info *proc;
1593 proc = current_process ();
1595 /* Check the cache first. */
1596 for (sym = proc->symbol_cache; sym; sym = sym->next)
1597 if (strcmp (name, sym->name) == 0)
1603 /* It might not be an appropriate time to look up a symbol,
1604 e.g. while we're trying to fetch registers. */
1608 /* Send the request. */
1609 strcpy (own_buf, "qSymbol:");
1610 hexify (own_buf + strlen ("qSymbol:"), name, strlen (name));
1611 if (putpkt (own_buf) < 0)
1614 /* FIXME: Eventually add buffer overflow checking (to getpkt?) */
1615 len = getpkt (own_buf);
1619 /* We ought to handle pretty much any packet at this point while we
1620 wait for the qSymbol "response". That requires re-entering the
1621 main loop. For now, this is an adequate approximation; allow
1622 GDB to read from memory while it figures out the address of the
1624 while (own_buf[0] == 'm')
1627 unsigned char *mem_buf;
1628 unsigned int mem_len;
1630 decode_m_packet (&own_buf[1], &mem_addr, &mem_len);
1631 mem_buf = xmalloc (mem_len);
1632 if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
1633 convert_int_to_ascii (mem_buf, own_buf, mem_len);
1635 write_enn (own_buf);
1637 if (putpkt (own_buf) < 0)
1639 len = getpkt (own_buf);
1644 if (strncmp (own_buf, "qSymbol:", strlen ("qSymbol:")) != 0)
1646 warning ("Malformed response to qSymbol, ignoring: %s\n", own_buf);
1650 p = own_buf + strlen ("qSymbol:");
1652 while (*q && *q != ':')
1655 /* Make sure we found a value for the symbol. */
1656 if (p == q || *q == '\0')
1659 decode_address (addrp, p, q - p);
1661 /* Save the symbol in our cache. */
1662 sym = xmalloc (sizeof (*sym));
1663 sym->name = xstrdup (name);
1665 sym->next = proc->symbol_cache;
1666 proc->symbol_cache = sym;
1671 /* Relocate an instruction to execute at a different address. OLDLOC
1672 is the address in the inferior memory where the instruction to
1673 relocate is currently at. On input, TO points to the destination
1674 where we want the instruction to be copied (and possibly adjusted)
1675 to. On output, it points to one past the end of the resulting
1676 instruction(s). The effect of executing the instruction at TO
1677 shall be the same as if executing it at OLDLOC. For example, call
1678 instructions that implicitly push the return address on the stack
1679 should be adjusted to return to the instruction after OLDLOC;
1680 relative branches, and other PC-relative instructions need the
1681 offset adjusted; etc. Returns 0 on success, -1 on failure. */
1684 relocate_instruction (CORE_ADDR *to, CORE_ADDR oldloc)
1688 ULONGEST written = 0;
1690 /* Send the request. */
1691 strcpy (own_buf, "qRelocInsn:");
1692 sprintf (own_buf, "qRelocInsn:%s;%s", paddress (oldloc),
1694 if (putpkt (own_buf) < 0)
1697 /* FIXME: Eventually add buffer overflow checking (to getpkt?) */
1698 len = getpkt (own_buf);
1702 /* We ought to handle pretty much any packet at this point while we
1703 wait for the qRelocInsn "response". That requires re-entering
1704 the main loop. For now, this is an adequate approximation; allow
1705 GDB to access memory. */
1706 while (own_buf[0] == 'm' || own_buf[0] == 'M' || own_buf[0] == 'X')
1709 unsigned char *mem_buf = NULL;
1710 unsigned int mem_len;
1712 if (own_buf[0] == 'm')
1714 decode_m_packet (&own_buf[1], &mem_addr, &mem_len);
1715 mem_buf = xmalloc (mem_len);
1716 if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
1717 convert_int_to_ascii (mem_buf, own_buf, mem_len);
1719 write_enn (own_buf);
1721 else if (own_buf[0] == 'X')
1723 if (decode_X_packet (&own_buf[1], len - 1, &mem_addr,
1724 &mem_len, &mem_buf) < 0
1725 || write_inferior_memory (mem_addr, mem_buf, mem_len) != 0)
1726 write_enn (own_buf);
1732 decode_M_packet (&own_buf[1], &mem_addr, &mem_len, &mem_buf);
1733 if (write_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
1736 write_enn (own_buf);
1739 if (putpkt (own_buf) < 0)
1741 len = getpkt (own_buf);
1746 if (own_buf[0] == 'E')
1748 warning ("An error occurred while relocating an instruction: %s\n",
1753 if (strncmp (own_buf, "qRelocInsn:", strlen ("qRelocInsn:")) != 0)
1755 warning ("Malformed response to qRelocInsn, ignoring: %s\n",
1760 unpack_varlen_hex (own_buf + strlen ("qRelocInsn:"), &written);
1767 monitor_output (const char *msg)
1769 char *buf = xmalloc (strlen (msg) * 2 + 2);
1772 hexify (buf + 1, msg, 0);