1/* Remote utility routines for the remote server for GDB.
2   Copyright (C) 1986, 1989, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3   2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
4
5   This file is part of GDB.
6
7   This program is free software; you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation; either version 3 of the License, or
10   (at your option) any later version.
11
12   This program is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20#include "server.h"
21#include "terminal.h"
22#include <stdio.h>
23#include <string.h>
24#if HAVE_SYS_IOCTL_H
25#include <sys/ioctl.h>
26#endif
27#if HAVE_SYS_FILE_H
28#include <sys/file.h>
29#endif
30#if HAVE_NETINET_IN_H
31#include <netinet/in.h>
32#endif
33#if HAVE_SYS_SOCKET_H
34#include <sys/socket.h>
35#endif
36#if HAVE_NETDB_H
37#include <netdb.h>
38#endif
39#if HAVE_NETINET_TCP_H
40#include <netinet/tcp.h>
41#endif
42#if HAVE_SYS_IOCTL_H
43#include <sys/ioctl.h>
44#endif
45#if HAVE_SIGNAL_H
46#include <signal.h>
47#endif
48#if HAVE_FCNTL_H
49#include <fcntl.h>
50#endif
51#include <sys/time.h>
52#if HAVE_UNISTD_H
53#include <unistd.h>
54#endif
55#if HAVE_ARPA_INET_H
56#include <arpa/inet.h>
57#endif
58#include <sys/stat.h>
59#if HAVE_ERRNO_H
60#include <errno.h>
61#endif
62
63#if USE_WIN32API
64#include <winsock.h>
65#endif
66
67#ifndef HAVE_SOCKLEN_T
68typedef int socklen_t;
69#endif
70
71#if USE_WIN32API
72# define INVALID_DESCRIPTOR INVALID_SOCKET
73#else
74# define INVALID_DESCRIPTOR -1
75#endif
76
77/* A cache entry for a successfully looked-up symbol.  */
78struct sym_cache
79{
80  const char *name;
81  CORE_ADDR addr;
82  struct sym_cache *next;
83};
84
85/* The symbol cache.  */
86static struct sym_cache *symbol_cache;
87
88/* If this flag has been set, assume cache misses are
89   failures.  */
90int all_symbols_looked_up;
91
92int remote_debug = 0;
93struct ui_file *gdb_stdlog;
94
95static int remote_desc = INVALID_DESCRIPTOR;
96
97/* FIXME headerize? */
98extern int using_threads;
99extern int debug_threads;
100
101#ifdef USE_WIN32API
102# define read(fd, buf, len) recv (fd, (char *) buf, len, 0)
103# define write(fd, buf, len) send (fd, (char *) buf, len, 0)
104#endif
105
106/* Open a connection to a remote debugger.
107   NAME is the filename used for communication.  */
108
109void
110remote_open (char *name)
111{
112#if defined(F_SETFL) && defined (FASYNC)
113  int save_fcntl_flags;
114#endif
115  char *port_str;
116
117  port_str = strchr (name, ':');
118  if (port_str == NULL)
119    {
120#ifdef USE_WIN32API
121      error ("Only <host>:<port> is supported on this platform.");
122#else
123      struct stat statbuf;
124
125      if (stat (name, &statbuf) == 0
126	  && (S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode)))
127	remote_desc = open (name, O_RDWR);
128      else
129	{
130	  errno = EINVAL;
131	  remote_desc = -1;
132	}
133
134      if (remote_desc < 0)
135	perror_with_name ("Could not open remote device");
136
137#ifdef HAVE_TERMIOS
138      {
139	struct termios termios;
140	tcgetattr (remote_desc, &termios);
141
142	termios.c_iflag = 0;
143	termios.c_oflag = 0;
144	termios.c_lflag = 0;
145	termios.c_cflag &= ~(CSIZE | PARENB);
146	termios.c_cflag |= CLOCAL | CS8;
147	termios.c_cc[VMIN] = 1;
148	termios.c_cc[VTIME] = 0;
149
150	tcsetattr (remote_desc, TCSANOW, &termios);
151      }
152#endif
153
154#ifdef HAVE_TERMIO
155      {
156	struct termio termio;
157	ioctl (remote_desc, TCGETA, &termio);
158
159	termio.c_iflag = 0;
160	termio.c_oflag = 0;
161	termio.c_lflag = 0;
162	termio.c_cflag &= ~(CSIZE | PARENB);
163	termio.c_cflag |= CLOCAL | CS8;
164	termio.c_cc[VMIN] = 1;
165	termio.c_cc[VTIME] = 0;
166
167	ioctl (remote_desc, TCSETA, &termio);
168      }
169#endif
170
171#ifdef HAVE_SGTTY
172      {
173	struct sgttyb sg;
174
175	ioctl (remote_desc, TIOCGETP, &sg);
176	sg.sg_flags = RAW;
177	ioctl (remote_desc, TIOCSETP, &sg);
178      }
179#endif
180
181      fprintf (stderr, "Remote debugging using %s\n", name);
182#endif /* USE_WIN32API */
183    }
184  else
185    {
186#ifdef USE_WIN32API
187      static int winsock_initialized;
188#endif
189      char *port_str;
190      int port;
191      struct sockaddr_in sockaddr;
192      socklen_t tmp;
193      int tmp_desc;
194
195      port_str = strchr (name, ':');
196
197      port = atoi (port_str + 1);
198
199#ifdef USE_WIN32API
200      if (!winsock_initialized)
201	{
202	  WSADATA wsad;
203
204	  WSAStartup (MAKEWORD (1, 0), &wsad);
205	  winsock_initialized = 1;
206	}
207#endif
208
209      tmp_desc = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
210      if (tmp_desc < 0)
211	perror_with_name ("Can't open socket");
212
213      /* Allow rapid reuse of this port. */
214      tmp = 1;
215      setsockopt (tmp_desc, SOL_SOCKET, SO_REUSEADDR, (char *) &tmp,
216		  sizeof (tmp));
217
218      sockaddr.sin_family = PF_INET;
219      sockaddr.sin_port = htons (port);
220      sockaddr.sin_addr.s_addr = INADDR_ANY;
221
222      if (bind (tmp_desc, (struct sockaddr *) &sockaddr, sizeof (sockaddr))
223	  || listen (tmp_desc, 1))
224	perror_with_name ("Can't bind address");
225
226      /* If port is zero, a random port will be selected, and the
227	 fprintf below needs to know what port was selected.  */
228      if (port == 0)
229	{
230	  socklen_t len = sizeof (sockaddr);
231	  if (getsockname (tmp_desc, (struct sockaddr *) &sockaddr, &len) < 0
232	      || len < sizeof (sockaddr))
233	    perror_with_name ("Can't determine port");
234	  port = ntohs (sockaddr.sin_port);
235	}
236
237      fprintf (stderr, "Listening on port %d\n", port);
238      fflush (stderr);
239
240      tmp = sizeof (sockaddr);
241      remote_desc = accept (tmp_desc, (struct sockaddr *) &sockaddr, &tmp);
242      if (remote_desc == -1)
243	perror_with_name ("Accept failed");
244
245      /* Enable TCP keep alive process. */
246      tmp = 1;
247      setsockopt (remote_desc, SOL_SOCKET, SO_KEEPALIVE,
248		  (char *) &tmp, sizeof (tmp));
249
250      /* Tell TCP not to delay small packets.  This greatly speeds up
251         interactive response. */
252      tmp = 1;
253      setsockopt (remote_desc, IPPROTO_TCP, TCP_NODELAY,
254		  (char *) &tmp, sizeof (tmp));
255
256
257#ifndef USE_WIN32API
258      close (tmp_desc);		/* No longer need this */
259
260      signal (SIGPIPE, SIG_IGN);	/* If we don't do this, then gdbserver simply
261					   exits when the remote side dies.  */
262#else
263      closesocket (tmp_desc);	/* No longer need this */
264#endif
265
266      /* Convert IP address to string.  */
267      fprintf (stderr, "Remote debugging from host %s\n",
268         inet_ntoa (sockaddr.sin_addr));
269    }
270
271#if defined(F_SETFL) && defined (FASYNC)
272  save_fcntl_flags = fcntl (remote_desc, F_GETFL, 0);
273  fcntl (remote_desc, F_SETFL, save_fcntl_flags | FASYNC);
274#if defined (F_SETOWN)
275  fcntl (remote_desc, F_SETOWN, getpid ());
276#endif
277#endif
278  disable_async_io ();
279}
280
281void
282remote_close (void)
283{
284#ifdef USE_WIN32API
285  closesocket (remote_desc);
286#else
287  close (remote_desc);
288#endif
289}
290
291/* Convert hex digit A to a number.  */
292
293static int
294fromhex (int a)
295{
296  if (a >= '0' && a <= '9')
297    return a - '0';
298  else if (a >= 'a' && a <= 'f')
299    return a - 'a' + 10;
300  else
301    error ("Reply contains invalid hex digit");
302  return 0;
303}
304
305int
306unhexify (char *bin, const char *hex, int count)
307{
308  int i;
309
310  for (i = 0; i < count; i++)
311    {
312      if (hex[0] == 0 || hex[1] == 0)
313        {
314          /* Hex string is short, or of uneven length.
315             Return the count that has been converted so far. */
316          return i;
317        }
318      *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
319      hex += 2;
320    }
321  return i;
322}
323
324void
325decode_address (CORE_ADDR *addrp, const char *start, int len)
326{
327  CORE_ADDR addr;
328  char ch;
329  int i;
330
331  addr = 0;
332  for (i = 0; i < len; i++)
333    {
334      ch = start[i];
335      addr = addr << 4;
336      addr = addr | (fromhex (ch) & 0x0f);
337    }
338  *addrp = addr;
339}
340
341const char *
342decode_address_to_semicolon (CORE_ADDR *addrp, const char *start)
343{
344  const char *end;
345
346  end = start;
347  while (*end != '\0' && *end != ';')
348    end++;
349
350  decode_address (addrp, start, end - start);
351
352  if (*end == ';')
353    end++;
354  return end;
355}
356
357/* Convert number NIB to a hex digit.  */
358
359static int
360tohex (int nib)
361{
362  if (nib < 10)
363    return '0' + nib;
364  else
365    return 'a' + nib - 10;
366}
367
368int
369hexify (char *hex, const char *bin, int count)
370{
371  int i;
372
373  /* May use a length, or a nul-terminated string as input. */
374  if (count == 0)
375    count = strlen (bin);
376
377  for (i = 0; i < count; i++)
378    {
379      *hex++ = tohex ((*bin >> 4) & 0xf);
380      *hex++ = tohex (*bin++ & 0xf);
381    }
382  *hex = 0;
383  return i;
384}
385
386/* Convert BUFFER, binary data at least LEN bytes long, into escaped
387   binary data in OUT_BUF.  Set *OUT_LEN to the length of the data
388   encoded in OUT_BUF, and return the number of bytes in OUT_BUF
389   (which may be more than *OUT_LEN due to escape characters).  The
390   total number of bytes in the output buffer will be at most
391   OUT_MAXLEN.  */
392
393int
394remote_escape_output (const gdb_byte *buffer, int len,
395		      gdb_byte *out_buf, int *out_len,
396		      int out_maxlen)
397{
398  int input_index, output_index;
399
400  output_index = 0;
401  for (input_index = 0; input_index < len; input_index++)
402    {
403      gdb_byte b = buffer[input_index];
404
405      if (b == '$' || b == '#' || b == '}' || b == '*')
406	{
407	  /* These must be escaped.  */
408	  if (output_index + 2 > out_maxlen)
409	    break;
410	  out_buf[output_index++] = '}';
411	  out_buf[output_index++] = b ^ 0x20;
412	}
413      else
414	{
415	  if (output_index + 1 > out_maxlen)
416	    break;
417	  out_buf[output_index++] = b;
418	}
419    }
420
421  *out_len = input_index;
422  return output_index;
423}
424
425/* Convert BUFFER, escaped data LEN bytes long, into binary data
426   in OUT_BUF.  Return the number of bytes written to OUT_BUF.
427   Raise an error if the total number of bytes exceeds OUT_MAXLEN.
428
429   This function reverses remote_escape_output.  It allows more
430   escaped characters than that function does, in particular because
431   '*' must be escaped to avoid the run-length encoding processing
432   in reading packets.  */
433
434static int
435remote_unescape_input (const gdb_byte *buffer, int len,
436		       gdb_byte *out_buf, int out_maxlen)
437{
438  int input_index, output_index;
439  int escaped;
440
441  output_index = 0;
442  escaped = 0;
443  for (input_index = 0; input_index < len; input_index++)
444    {
445      gdb_byte b = buffer[input_index];
446
447      if (output_index + 1 > out_maxlen)
448	error ("Received too much data from the target.");
449
450      if (escaped)
451	{
452	  out_buf[output_index++] = b ^ 0x20;
453	  escaped = 0;
454	}
455      else if (b == '}')
456	escaped = 1;
457      else
458	out_buf[output_index++] = b;
459    }
460
461  if (escaped)
462    error ("Unmatched escape character in target response.");
463
464  return output_index;
465}
466
467/* Look for a sequence of characters which can be run-length encoded.
468   If there are any, update *CSUM and *P.  Otherwise, output the
469   single character.  Return the number of characters consumed.  */
470
471static int
472try_rle (char *buf, int remaining, unsigned char *csum, char **p)
473{
474  int n;
475
476  /* Always output the character.  */
477  *csum += buf[0];
478  *(*p)++ = buf[0];
479
480  /* Don't go past '~'.  */
481  if (remaining > 97)
482    remaining = 97;
483
484  for (n = 1; n < remaining; n++)
485    if (buf[n] != buf[0])
486      break;
487
488  /* N is the index of the first character not the same as buf[0].
489     buf[0] is counted twice, so by decrementing N, we get the number
490     of characters the RLE sequence will replace.  */
491  n--;
492
493  if (n < 3)
494    return 1;
495
496  /* Skip the frame characters.  The manual says to skip '+' and '-'
497     also, but there's no reason to.  Unfortunately these two unusable
498     characters double the encoded length of a four byte zero
499     value.  */
500  while (n + 29 == '$' || n + 29 == '#')
501    n--;
502
503  *csum += '*';
504  *(*p)++ = '*';
505  *csum += n + 29;
506  *(*p)++ = n + 29;
507
508  return n + 1;
509}
510
511/* Send a packet to the remote machine, with error checking.
512   The data of the packet is in BUF, and the length of the
513   packet is in CNT.  Returns >= 0 on success, -1 otherwise.  */
514
515int
516putpkt_binary (char *buf, int cnt)
517{
518  int i;
519  unsigned char csum = 0;
520  char *buf2;
521  char buf3[1];
522  char *p;
523
524  buf2 = malloc (PBUFSIZ);
525
526  /* Copy the packet into buffer BUF2, encapsulating it
527     and giving it a checksum.  */
528
529  p = buf2;
530  *p++ = '$';
531
532  for (i = 0; i < cnt;)
533    i += try_rle (buf + i, cnt - i, &csum, &p);
534
535  *p++ = '#';
536  *p++ = tohex ((csum >> 4) & 0xf);
537  *p++ = tohex (csum & 0xf);
538
539  *p = '\0';
540
541  /* Send it over and over until we get a positive ack.  */
542
543  do
544    {
545      int cc;
546
547      if (write (remote_desc, buf2, p - buf2) != p - buf2)
548	{
549	  perror ("putpkt(write)");
550	  free (buf2);
551	  return -1;
552	}
553
554      if (remote_debug)
555	{
556	  fprintf (stderr, "putpkt (\"%s\"); [looking for ack]\n", buf2);
557	  fflush (stderr);
558	}
559      cc = read (remote_desc, buf3, 1);
560      if (remote_debug)
561	{
562	  fprintf (stderr, "[received '%c' (0x%x)]\n", buf3[0], buf3[0]);
563	  fflush (stderr);
564	}
565
566      if (cc <= 0)
567	{
568	  if (cc == 0)
569	    fprintf (stderr, "putpkt(read): Got EOF\n");
570	  else
571	    perror ("putpkt(read)");
572
573	  free (buf2);
574	  return -1;
575	}
576
577      /* Check for an input interrupt while we're here.  */
578      if (buf3[0] == '\003')
579	(*the_target->request_interrupt) ();
580    }
581  while (buf3[0] != '+');
582
583  free (buf2);
584  return 1;			/* Success! */
585}
586
587/* Send a packet to the remote machine, with error checking.  The data
588   of the packet is in BUF, and the packet should be a NUL-terminated
589   string.  Returns >= 0 on success, -1 otherwise.  */
590
591int
592putpkt (char *buf)
593{
594  return putpkt_binary (buf, strlen (buf));
595}
596
597/* Come here when we get an input interrupt from the remote side.  This
598   interrupt should only be active while we are waiting for the child to do
599   something.  About the only thing that should come through is a ^C, which
600   will cause us to request child interruption.  */
601
602static void
603input_interrupt (int unused)
604{
605  fd_set readset;
606  struct timeval immediate = { 0, 0 };
607
608  /* Protect against spurious interrupts.  This has been observed to
609     be a problem under NetBSD 1.4 and 1.5.  */
610
611  FD_ZERO (&readset);
612  FD_SET (remote_desc, &readset);
613  if (select (remote_desc + 1, &readset, 0, 0, &immediate) > 0)
614    {
615      int cc;
616      char c = 0;
617
618      cc = read (remote_desc, &c, 1);
619
620      if (cc != 1 || c != '\003')
621	{
622	  fprintf (stderr, "input_interrupt, count = %d c = %d ('%c')\n",
623		   cc, c, c);
624	  return;
625	}
626
627      (*the_target->request_interrupt) ();
628    }
629}
630
631/* Check if the remote side sent us an interrupt request (^C).  */
632void
633check_remote_input_interrupt_request (void)
634{
635  /* This function may be called before establishing communications,
636     therefore we need to validate the remote descriptor.  */
637
638  if (remote_desc == INVALID_DESCRIPTOR)
639    return;
640
641  input_interrupt (0);
642}
643
644/* Asynchronous I/O support.  SIGIO must be enabled when waiting, in order to
645   accept Control-C from the client, and must be disabled when talking to
646   the client.  */
647
648void
649block_async_io (void)
650{
651#ifndef USE_WIN32API
652  sigset_t sigio_set;
653  sigemptyset (&sigio_set);
654  sigaddset (&sigio_set, SIGIO);
655  sigprocmask (SIG_BLOCK, &sigio_set, NULL);
656#endif
657}
658
659void
660unblock_async_io (void)
661{
662#ifndef USE_WIN32API
663  sigset_t sigio_set;
664  sigemptyset (&sigio_set);
665  sigaddset (&sigio_set, SIGIO);
666  sigprocmask (SIG_UNBLOCK, &sigio_set, NULL);
667#endif
668}
669
670/* Current state of asynchronous I/O.  */
671static int async_io_enabled;
672
673/* Enable asynchronous I/O.  */
674void
675enable_async_io (void)
676{
677  if (async_io_enabled)
678    return;
679
680#ifndef USE_WIN32API
681  signal (SIGIO, input_interrupt);
682#endif
683  async_io_enabled = 1;
684}
685
686/* Disable asynchronous I/O.  */
687void
688disable_async_io (void)
689{
690  if (!async_io_enabled)
691    return;
692
693#ifndef USE_WIN32API
694  signal (SIGIO, SIG_IGN);
695#endif
696  async_io_enabled = 0;
697}
698
699/* Returns next char from remote GDB.  -1 if error.  */
700
701static int
702readchar (void)
703{
704  static unsigned char buf[BUFSIZ];
705  static int bufcnt = 0;
706  static unsigned char *bufp;
707
708  if (bufcnt-- > 0)
709    return *bufp++;
710
711  bufcnt = read (remote_desc, buf, sizeof (buf));
712
713  if (bufcnt <= 0)
714    {
715      if (bufcnt == 0)
716	fprintf (stderr, "readchar: Got EOF\n");
717      else
718	perror ("readchar");
719
720      return -1;
721    }
722
723  bufp = buf;
724  bufcnt--;
725  return *bufp++ & 0x7f;
726}
727
728/* Read a packet from the remote machine, with error checking,
729   and store it in BUF.  Returns length of packet, or negative if error. */
730
731int
732getpkt (char *buf)
733{
734  char *bp;
735  unsigned char csum, c1, c2;
736  int c;
737
738  while (1)
739    {
740      csum = 0;
741
742      while (1)
743	{
744	  c = readchar ();
745	  if (c == '$')
746	    break;
747	  if (remote_debug)
748	    {
749	      fprintf (stderr, "[getpkt: discarding char '%c']\n", c);
750	      fflush (stderr);
751	    }
752
753	  if (c < 0)
754	    return -1;
755	}
756
757      bp = buf;
758      while (1)
759	{
760	  c = readchar ();
761	  if (c < 0)
762	    return -1;
763	  if (c == '#')
764	    break;
765	  *bp++ = c;
766	  csum += c;
767	}
768      *bp = 0;
769
770      c1 = fromhex (readchar ());
771      c2 = fromhex (readchar ());
772
773      if (csum == (c1 << 4) + c2)
774	break;
775
776      fprintf (stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
777	       (c1 << 4) + c2, csum, buf);
778      write (remote_desc, "-", 1);
779    }
780
781  if (remote_debug)
782    {
783      fprintf (stderr, "getpkt (\"%s\");  [sending ack] \n", buf);
784      fflush (stderr);
785    }
786
787  write (remote_desc, "+", 1);
788
789  if (remote_debug)
790    {
791      fprintf (stderr, "[sent ack]\n");
792      fflush (stderr);
793    }
794
795  return bp - buf;
796}
797
798void
799write_ok (char *buf)
800{
801  buf[0] = 'O';
802  buf[1] = 'K';
803  buf[2] = '\0';
804}
805
806void
807write_enn (char *buf)
808{
809  /* Some day, we should define the meanings of the error codes... */
810  buf[0] = 'E';
811  buf[1] = '0';
812  buf[2] = '1';
813  buf[3] = '\0';
814}
815
816void
817convert_int_to_ascii (unsigned char *from, char *to, int n)
818{
819  int nib;
820  int ch;
821  while (n--)
822    {
823      ch = *from++;
824      nib = ((ch & 0xf0) >> 4) & 0x0f;
825      *to++ = tohex (nib);
826      nib = ch & 0x0f;
827      *to++ = tohex (nib);
828    }
829  *to++ = 0;
830}
831
832
833void
834convert_ascii_to_int (char *from, unsigned char *to, int n)
835{
836  int nib1, nib2;
837  while (n--)
838    {
839      nib1 = fromhex (*from++);
840      nib2 = fromhex (*from++);
841      *to++ = (((nib1 & 0x0f) << 4) & 0xf0) | (nib2 & 0x0f);
842    }
843}
844
845static char *
846outreg (int regno, char *buf)
847{
848  if ((regno >> 12) != 0)
849    *buf++ = tohex ((regno >> 12) & 0xf);
850  if ((regno >> 8) != 0)
851    *buf++ = tohex ((regno >> 8) & 0xf);
852  *buf++ = tohex ((regno >> 4) & 0xf);
853  *buf++ = tohex (regno & 0xf);
854  *buf++ = ':';
855  collect_register_as_string (regno, buf);
856  buf += 2 * register_size (regno);
857  *buf++ = ';';
858
859  return buf;
860}
861
862void
863new_thread_notify (int id)
864{
865  char own_buf[256];
866
867  /* The `n' response is not yet part of the remote protocol.  Do nothing.  */
868  if (1)
869    return;
870
871  if (server_waiting == 0)
872    return;
873
874  sprintf (own_buf, "n%x", id);
875  disable_async_io ();
876  putpkt (own_buf);
877  enable_async_io ();
878}
879
880void
881dead_thread_notify (int id)
882{
883  char own_buf[256];
884
885  /* The `x' response is not yet part of the remote protocol.  Do nothing.  */
886  if (1)
887    return;
888
889  sprintf (own_buf, "x%x", id);
890  disable_async_io ();
891  putpkt (own_buf);
892  enable_async_io ();
893}
894
895void
896prepare_resume_reply (char *buf, char status, unsigned char sig)
897{
898  int nib;
899
900  *buf++ = status;
901
902  nib = ((sig & 0xf0) >> 4);
903  *buf++ = tohex (nib);
904  nib = sig & 0x0f;
905  *buf++ = tohex (nib);
906
907  if (status == 'T')
908    {
909      const char **regp = gdbserver_expedite_regs;
910
911      if (the_target->stopped_by_watchpoint != NULL
912	  && (*the_target->stopped_by_watchpoint) ())
913	{
914	  CORE_ADDR addr;
915	  int i;
916
917	  strncpy (buf, "watch:", 6);
918	  buf += 6;
919
920	  addr = (*the_target->stopped_data_address) ();
921
922	  /* Convert each byte of the address into two hexadecimal chars.
923	     Note that we take sizeof (void *) instead of sizeof (addr);
924	     this is to avoid sending a 64-bit address to a 32-bit GDB.  */
925	  for (i = sizeof (void *) * 2; i > 0; i--)
926	    {
927	      *buf++ = tohex ((addr >> (i - 1) * 4) & 0xf);
928	    }
929	  *buf++ = ';';
930	}
931
932      while (*regp)
933	{
934	  buf = outreg (find_regno (*regp), buf);
935	  regp ++;
936	}
937
938      /* Formerly, if the debugger had not used any thread features we would not
939	 burden it with a thread status response.  This was for the benefit of
940	 GDB 4.13 and older.  However, in recent GDB versions the check
941	 (``if (cont_thread != 0)'') does not have the desired effect because of
942	 sillyness in the way that the remote protocol handles specifying a thread.
943	 Since thread support relies on qSymbol support anyway, assume GDB can handle
944	 threads.  */
945
946      if (using_threads)
947	{
948	  unsigned int gdb_id_from_wait;
949
950	  /* FIXME right place to set this? */
951	  thread_from_wait = ((struct inferior_list_entry *)current_inferior)->id;
952	  gdb_id_from_wait = thread_to_gdb_id (current_inferior);
953
954	  if (debug_threads)
955	    fprintf (stderr, "Writing resume reply for %ld\n\n", thread_from_wait);
956	  /* This if (1) ought to be unnecessary.  But remote_wait in GDB
957	     will claim this event belongs to inferior_ptid if we do not
958	     specify a thread, and there's no way for gdbserver to know
959	     what inferior_ptid is.  */
960	  if (1 || old_thread_from_wait != thread_from_wait)
961	    {
962	      general_thread = thread_from_wait;
963	      sprintf (buf, "thread:%x;", gdb_id_from_wait);
964	      buf += strlen (buf);
965	      old_thread_from_wait = thread_from_wait;
966	    }
967	}
968
969      if (dlls_changed)
970	{
971	  strcpy (buf, "library:;");
972	  buf += strlen (buf);
973	  dlls_changed = 0;
974	}
975    }
976  /* For W and X, we're done.  */
977  *buf++ = 0;
978}
979
980void
981decode_m_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr)
982{
983  int i = 0, j = 0;
984  char ch;
985  *mem_addr_ptr = *len_ptr = 0;
986
987  while ((ch = from[i++]) != ',')
988    {
989      *mem_addr_ptr = *mem_addr_ptr << 4;
990      *mem_addr_ptr |= fromhex (ch) & 0x0f;
991    }
992
993  for (j = 0; j < 4; j++)
994    {
995      if ((ch = from[i++]) == 0)
996	break;
997      *len_ptr = *len_ptr << 4;
998      *len_ptr |= fromhex (ch) & 0x0f;
999    }
1000}
1001
1002void
1003decode_M_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr,
1004		 unsigned char *to)
1005{
1006  int i = 0;
1007  char ch;
1008  *mem_addr_ptr = *len_ptr = 0;
1009
1010  while ((ch = from[i++]) != ',')
1011    {
1012      *mem_addr_ptr = *mem_addr_ptr << 4;
1013      *mem_addr_ptr |= fromhex (ch) & 0x0f;
1014    }
1015
1016  while ((ch = from[i++]) != ':')
1017    {
1018      *len_ptr = *len_ptr << 4;
1019      *len_ptr |= fromhex (ch) & 0x0f;
1020    }
1021
1022  convert_ascii_to_int (&from[i++], to, *len_ptr);
1023}
1024
1025int
1026decode_X_packet (char *from, int packet_len, CORE_ADDR *mem_addr_ptr,
1027		 unsigned int *len_ptr, unsigned char *to)
1028{
1029  int i = 0;
1030  char ch;
1031  *mem_addr_ptr = *len_ptr = 0;
1032
1033  while ((ch = from[i++]) != ',')
1034    {
1035      *mem_addr_ptr = *mem_addr_ptr << 4;
1036      *mem_addr_ptr |= fromhex (ch) & 0x0f;
1037    }
1038
1039  while ((ch = from[i++]) != ':')
1040    {
1041      *len_ptr = *len_ptr << 4;
1042      *len_ptr |= fromhex (ch) & 0x0f;
1043    }
1044
1045  if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len - i,
1046			     to, *len_ptr) != *len_ptr)
1047    return -1;
1048
1049  return 0;
1050}
1051
1052/* Decode a qXfer write request.  */
1053int
1054decode_xfer_write (char *buf, int packet_len, char **annex, CORE_ADDR *offset,
1055		   unsigned int *len, unsigned char *data)
1056{
1057  char ch;
1058
1059  /* Extract and NUL-terminate the annex.  */
1060  *annex = buf;
1061  while (*buf && *buf != ':')
1062    buf++;
1063  if (*buf == '\0')
1064    return -1;
1065  *buf++ = 0;
1066
1067  /* Extract the offset.  */
1068  *offset = 0;
1069  while ((ch = *buf++) != ':')
1070    {
1071      *offset = *offset << 4;
1072      *offset |= fromhex (ch) & 0x0f;
1073    }
1074
1075  /* Get encoded data.  */
1076  packet_len -= buf - *annex;
1077  *len = remote_unescape_input ((const gdb_byte *) buf, packet_len,
1078				data, packet_len);
1079  return 0;
1080}
1081
1082/* Ask GDB for the address of NAME, and return it in ADDRP if found.
1083   Returns 1 if the symbol is found, 0 if it is not, -1 on error.  */
1084
1085int
1086look_up_one_symbol (const char *name, CORE_ADDR *addrp)
1087{
1088  char own_buf[266], *p, *q;
1089  int len;
1090  struct sym_cache *sym;
1091
1092  /* Check the cache first.  */
1093  for (sym = symbol_cache; sym; sym = sym->next)
1094    if (strcmp (name, sym->name) == 0)
1095      {
1096	*addrp = sym->addr;
1097	return 1;
1098      }
1099
1100  /* If we've passed the call to thread_db_look_up_symbols, then
1101     anything not in the cache must not exist; we're not interested
1102     in any libraries loaded after that point, only in symbols in
1103     libpthread.so.  It might not be an appropriate time to look
1104     up a symbol, e.g. while we're trying to fetch registers.  */
1105  if (all_symbols_looked_up)
1106    return 0;
1107
1108  /* Send the request.  */
1109  strcpy (own_buf, "qSymbol:");
1110  hexify (own_buf + strlen ("qSymbol:"), name, strlen (name));
1111  if (putpkt (own_buf) < 0)
1112    return -1;
1113
1114  /* FIXME:  Eventually add buffer overflow checking (to getpkt?)  */
1115  len = getpkt (own_buf);
1116  if (len < 0)
1117    return -1;
1118
1119  /* We ought to handle pretty much any packet at this point while we
1120     wait for the qSymbol "response".  That requires re-entering the
1121     main loop.  For now, this is an adequate approximation; allow
1122     GDB to read from memory while it figures out the address of the
1123     symbol.  */
1124  while (own_buf[0] == 'm')
1125    {
1126      CORE_ADDR mem_addr;
1127      unsigned char *mem_buf;
1128      unsigned int mem_len;
1129
1130      decode_m_packet (&own_buf[1], &mem_addr, &mem_len);
1131      mem_buf = malloc (mem_len);
1132      if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
1133	convert_int_to_ascii (mem_buf, own_buf, mem_len);
1134      else
1135	write_enn (own_buf);
1136      free (mem_buf);
1137      if (putpkt (own_buf) < 0)
1138	return -1;
1139      len = getpkt (own_buf);
1140      if (len < 0)
1141	return -1;
1142    }
1143
1144  if (strncmp (own_buf, "qSymbol:", strlen ("qSymbol:")) != 0)
1145    {
1146      warning ("Malformed response to qSymbol, ignoring: %s\n", own_buf);
1147      return -1;
1148    }
1149
1150  p = own_buf + strlen ("qSymbol:");
1151  q = p;
1152  while (*q && *q != ':')
1153    q++;
1154
1155  /* Make sure we found a value for the symbol.  */
1156  if (p == q || *q == '\0')
1157    return 0;
1158
1159  decode_address (addrp, p, q - p);
1160
1161  /* Save the symbol in our cache.  */
1162  sym = malloc (sizeof (*sym));
1163  sym->name = strdup (name);
1164  sym->addr = *addrp;
1165  sym->next = symbol_cache;
1166  symbol_cache = sym;
1167
1168  return 1;
1169}
1170
1171void
1172monitor_output (const char *msg)
1173{
1174  char *buf = malloc (strlen (msg) * 2 + 2);
1175
1176  buf[0] = 'O';
1177  hexify (buf + 1, msg, 0);
1178
1179  putpkt (buf);
1180  free (buf);
1181}
1182
1183/* Return a malloc allocated string with special characters from TEXT
1184   replaced by entity references.  */
1185
1186char *
1187xml_escape_text (const char *text)
1188{
1189  char *result;
1190  int i, special;
1191
1192  /* Compute the length of the result.  */
1193  for (i = 0, special = 0; text[i] != '\0'; i++)
1194    switch (text[i])
1195      {
1196      case '\'':
1197      case '\"':
1198	special += 5;
1199	break;
1200      case '&':
1201	special += 4;
1202	break;
1203      case '<':
1204      case '>':
1205	special += 3;
1206	break;
1207      default:
1208	break;
1209      }
1210
1211  /* Expand the result.  */
1212  result = malloc (i + special + 1);
1213  for (i = 0, special = 0; text[i] != '\0'; i++)
1214    switch (text[i])
1215      {
1216      case '\'':
1217	strcpy (result + i + special, "&apos;");
1218	special += 5;
1219	break;
1220      case '\"':
1221	strcpy (result + i + special, "&quot;");
1222	special += 5;
1223	break;
1224      case '&':
1225	strcpy (result + i + special, "&amp;");
1226	special += 4;
1227	break;
1228      case '<':
1229	strcpy (result + i + special, "&lt;");
1230	special += 3;
1231	break;
1232      case '>':
1233	strcpy (result + i + special, "&gt;");
1234	special += 3;
1235	break;
1236      default:
1237	result[i + special] = text[i];
1238	break;
1239      }
1240  result[i + special] = '\0';
1241
1242  return result;
1243}
1244