1/* Remote utility routines for the remote server for GDB.
2   Copyright 1986, 1989, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
3   2002, 2003, 2004
4   Free Software Foundation, Inc.
5
6   This file is part of GDB.
7
8   This program is free software; you can redistribute it and/or modify
9   it under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with this program; if not, write to the Free Software
20   Foundation, Inc., 59 Temple Place - Suite 330,
21   Boston, MA 02111-1307, USA.  */
22
23#include "server.h"
24#include "terminal.h"
25#include <stdio.h>
26#include <string.h>
27#include <sys/ioctl.h>
28#include <sys/file.h>
29#include <netinet/in.h>
30#include <sys/socket.h>
31#include <netdb.h>
32#include <netinet/tcp.h>
33#include <sys/ioctl.h>
34#include <signal.h>
35#include <fcntl.h>
36#include <sys/time.h>
37#include <unistd.h>
38#include <arpa/inet.h>
39
40/* A cache entry for a successfully looked-up symbol.  */
41struct sym_cache
42{
43  const char *name;
44  CORE_ADDR addr;
45  struct sym_cache *next;
46};
47
48/* The symbol cache.  */
49static struct sym_cache *symbol_cache;
50
51int remote_debug = 0;
52struct ui_file *gdb_stdlog;
53
54static int remote_desc;
55
56/* FIXME headerize? */
57extern int using_threads;
58extern int debug_threads;
59
60/* Open a connection to a remote debugger.
61   NAME is the filename used for communication.  */
62
63void
64remote_open (char *name)
65{
66  int save_fcntl_flags;
67
68  if (!strchr (name, ':'))
69    {
70      remote_desc = open (name, O_RDWR);
71      if (remote_desc < 0)
72	perror_with_name ("Could not open remote device");
73
74#ifdef HAVE_TERMIOS
75      {
76	struct termios termios;
77	tcgetattr (remote_desc, &termios);
78
79	termios.c_iflag = 0;
80	termios.c_oflag = 0;
81	termios.c_lflag = 0;
82	termios.c_cflag &= ~(CSIZE | PARENB);
83	termios.c_cflag |= CLOCAL | CS8;
84	termios.c_cc[VMIN] = 1;
85	termios.c_cc[VTIME] = 0;
86
87	tcsetattr (remote_desc, TCSANOW, &termios);
88      }
89#endif
90
91#ifdef HAVE_TERMIO
92      {
93	struct termio termio;
94	ioctl (remote_desc, TCGETA, &termio);
95
96	termio.c_iflag = 0;
97	termio.c_oflag = 0;
98	termio.c_lflag = 0;
99	termio.c_cflag &= ~(CSIZE | PARENB);
100	termio.c_cflag |= CLOCAL | CS8;
101	termio.c_cc[VMIN] = 1;
102	termio.c_cc[VTIME] = 0;
103
104	ioctl (remote_desc, TCSETA, &termio);
105      }
106#endif
107
108#ifdef HAVE_SGTTY
109      {
110	struct sgttyb sg;
111
112	ioctl (remote_desc, TIOCGETP, &sg);
113	sg.sg_flags = RAW;
114	ioctl (remote_desc, TIOCSETP, &sg);
115      }
116#endif
117
118      fprintf (stderr, "Remote debugging using %s\n", name);
119    }
120  else
121    {
122      char *port_str;
123      int port;
124      struct sockaddr_in sockaddr;
125      int tmp;
126      int tmp_desc;
127
128      port_str = strchr (name, ':');
129
130      port = atoi (port_str + 1);
131
132      tmp_desc = socket (PF_INET, SOCK_STREAM, 0);
133      if (tmp_desc < 0)
134	perror_with_name ("Can't open socket");
135
136      /* Allow rapid reuse of this port. */
137      tmp = 1;
138      setsockopt (tmp_desc, SOL_SOCKET, SO_REUSEADDR, (char *) &tmp,
139		  sizeof (tmp));
140
141      sockaddr.sin_family = PF_INET;
142      sockaddr.sin_port = htons (port);
143      sockaddr.sin_addr.s_addr = INADDR_ANY;
144
145      if (bind (tmp_desc, (struct sockaddr *) &sockaddr, sizeof (sockaddr))
146	  || listen (tmp_desc, 1))
147	perror_with_name ("Can't bind address");
148
149      fprintf (stderr, "Listening on port %d\n", port);
150
151      tmp = sizeof (sockaddr);
152      remote_desc = accept (tmp_desc, (struct sockaddr *) &sockaddr, &tmp);
153      if (remote_desc == -1)
154	perror_with_name ("Accept failed");
155
156      /* Enable TCP keep alive process. */
157      tmp = 1;
158      setsockopt (tmp_desc, SOL_SOCKET, SO_KEEPALIVE, (char *) &tmp, sizeof (tmp));
159
160      /* Tell TCP not to delay small packets.  This greatly speeds up
161         interactive response. */
162      tmp = 1;
163      setsockopt (remote_desc, IPPROTO_TCP, TCP_NODELAY,
164		  (char *) &tmp, sizeof (tmp));
165
166      close (tmp_desc);		/* No longer need this */
167
168      signal (SIGPIPE, SIG_IGN);	/* If we don't do this, then gdbserver simply
169					   exits when the remote side dies.  */
170
171      /* Convert IP address to string.  */
172      fprintf (stderr, "Remote debugging from host %s\n",
173         inet_ntoa (sockaddr.sin_addr));
174    }
175
176#if defined(F_SETFL) && defined (FASYNC)
177  save_fcntl_flags = fcntl (remote_desc, F_GETFL, 0);
178  fcntl (remote_desc, F_SETFL, save_fcntl_flags | FASYNC);
179#if defined (F_SETOWN)
180  fcntl (remote_desc, F_SETOWN, getpid ());
181#endif
182#endif
183  disable_async_io ();
184}
185
186void
187remote_close (void)
188{
189  close (remote_desc);
190}
191
192/* Convert hex digit A to a number.  */
193
194static int
195fromhex (int a)
196{
197  if (a >= '0' && a <= '9')
198    return a - '0';
199  else if (a >= 'a' && a <= 'f')
200    return a - 'a' + 10;
201  else
202    error ("Reply contains invalid hex digit");
203  return 0;
204}
205
206int
207unhexify (char *bin, const char *hex, int count)
208{
209  int i;
210
211  for (i = 0; i < count; i++)
212    {
213      if (hex[0] == 0 || hex[1] == 0)
214        {
215          /* Hex string is short, or of uneven length.
216             Return the count that has been converted so far. */
217          return i;
218        }
219      *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
220      hex += 2;
221    }
222  return i;
223}
224
225static void
226decode_address (CORE_ADDR *addrp, const char *start, int len)
227{
228  CORE_ADDR addr;
229  char ch;
230  int i;
231
232  addr = 0;
233  for (i = 0; i < len; i++)
234    {
235      ch = start[i];
236      addr = addr << 4;
237      addr = addr | (fromhex (ch) & 0x0f);
238    }
239  *addrp = addr;
240}
241
242/* Convert number NIB to a hex digit.  */
243
244static int
245tohex (int nib)
246{
247  if (nib < 10)
248    return '0' + nib;
249  else
250    return 'a' + nib - 10;
251}
252
253int
254hexify (char *hex, const char *bin, int count)
255{
256  int i;
257
258  /* May use a length, or a nul-terminated string as input. */
259  if (count == 0)
260    count = strlen (bin);
261
262  for (i = 0; i < count; i++)
263    {
264      *hex++ = tohex ((*bin >> 4) & 0xf);
265      *hex++ = tohex (*bin++ & 0xf);
266    }
267  *hex = 0;
268  return i;
269}
270
271/* Send a packet to the remote machine, with error checking.
272   The data of the packet is in BUF.  Returns >= 0 on success, -1 otherwise. */
273
274int
275putpkt (char *buf)
276{
277  int i;
278  unsigned char csum = 0;
279  char *buf2;
280  char buf3[1];
281  int cnt = strlen (buf);
282  char *p;
283
284  buf2 = malloc (PBUFSIZ);
285
286  /* Copy the packet into buffer BUF2, encapsulating it
287     and giving it a checksum.  */
288
289  p = buf2;
290  *p++ = '$';
291
292  for (i = 0; i < cnt; i++)
293    {
294      csum += buf[i];
295      *p++ = buf[i];
296    }
297  *p++ = '#';
298  *p++ = tohex ((csum >> 4) & 0xf);
299  *p++ = tohex (csum & 0xf);
300
301  *p = '\0';
302
303  /* Send it over and over until we get a positive ack.  */
304
305  do
306    {
307      int cc;
308
309      if (write (remote_desc, buf2, p - buf2) != p - buf2)
310	{
311	  perror ("putpkt(write)");
312	  return -1;
313	}
314
315      if (remote_debug)
316	{
317	  fprintf (stderr, "putpkt (\"%s\"); [looking for ack]\n", buf2);
318	  fflush (stderr);
319	}
320      cc = read (remote_desc, buf3, 1);
321      if (remote_debug)
322	{
323	  fprintf (stderr, "[received '%c' (0x%x)]\n", buf3[0], buf3[0]);
324	  fflush (stderr);
325	}
326
327      if (cc <= 0)
328	{
329	  if (cc == 0)
330	    fprintf (stderr, "putpkt(read): Got EOF\n");
331	  else
332	    perror ("putpkt(read)");
333
334	  free (buf2);
335	  return -1;
336	}
337
338      /* Check for an input interrupt while we're here.  */
339      if (buf3[0] == '\003')
340	(*the_target->send_signal) (SIGINT);
341    }
342  while (buf3[0] != '+');
343
344  free (buf2);
345  return 1;			/* Success! */
346}
347
348/* Come here when we get an input interrupt from the remote side.  This
349   interrupt should only be active while we are waiting for the child to do
350   something.  About the only thing that should come through is a ^C, which
351   will cause us to send a SIGINT to the child.  */
352
353static void
354input_interrupt (int unused)
355{
356  fd_set readset;
357  struct timeval immediate = { 0, 0 };
358
359  /* Protect against spurious interrupts.  This has been observed to
360     be a problem under NetBSD 1.4 and 1.5.  */
361
362  FD_ZERO (&readset);
363  FD_SET (remote_desc, &readset);
364  if (select (remote_desc + 1, &readset, 0, 0, &immediate) > 0)
365    {
366      int cc;
367      char c = 0;
368
369      cc = read (remote_desc, &c, 1);
370
371      if (cc != 1 || c != '\003')
372	{
373	  fprintf (stderr, "input_interrupt, count = %d c = %d ('%c')\n",
374		   cc, c, c);
375	  return;
376	}
377
378      (*the_target->send_signal) (SIGINT);
379    }
380}
381
382void
383block_async_io (void)
384{
385  sigset_t sigio_set;
386  sigemptyset (&sigio_set);
387  sigaddset (&sigio_set, SIGIO);
388  sigprocmask (SIG_BLOCK, &sigio_set, NULL);
389}
390
391void
392unblock_async_io (void)
393{
394  sigset_t sigio_set;
395  sigemptyset (&sigio_set);
396  sigaddset (&sigio_set, SIGIO);
397  sigprocmask (SIG_UNBLOCK, &sigio_set, NULL);
398}
399
400/* Asynchronous I/O support.  SIGIO must be enabled when waiting, in order to
401   accept Control-C from the client, and must be disabled when talking to
402   the client.  */
403
404/* Current state of asynchronous I/O.  */
405static int async_io_enabled;
406
407/* Enable asynchronous I/O.  */
408void
409enable_async_io (void)
410{
411  if (async_io_enabled)
412    return;
413
414  signal (SIGIO, input_interrupt);
415  async_io_enabled = 1;
416}
417
418/* Disable asynchronous I/O.  */
419void
420disable_async_io (void)
421{
422  if (!async_io_enabled)
423    return;
424
425  signal (SIGIO, SIG_IGN);
426  async_io_enabled = 0;
427}
428
429/* Returns next char from remote GDB.  -1 if error.  */
430
431static int
432readchar (void)
433{
434  static char buf[BUFSIZ];
435  static int bufcnt = 0;
436  static char *bufp;
437
438  if (bufcnt-- > 0)
439    return *bufp++ & 0x7f;
440
441  bufcnt = read (remote_desc, buf, sizeof (buf));
442
443  if (bufcnt <= 0)
444    {
445      if (bufcnt == 0)
446	fprintf (stderr, "readchar: Got EOF\n");
447      else
448	perror ("readchar");
449
450      return -1;
451    }
452
453  bufp = buf;
454  bufcnt--;
455  return *bufp++ & 0x7f;
456}
457
458/* Read a packet from the remote machine, with error checking,
459   and store it in BUF.  Returns length of packet, or negative if error. */
460
461int
462getpkt (char *buf)
463{
464  char *bp;
465  unsigned char csum, c1, c2;
466  int c;
467
468  while (1)
469    {
470      csum = 0;
471
472      while (1)
473	{
474	  c = readchar ();
475	  if (c == '$')
476	    break;
477	  if (remote_debug)
478	    {
479	      fprintf (stderr, "[getpkt: discarding char '%c']\n", c);
480	      fflush (stderr);
481	    }
482
483	  if (c < 0)
484	    return -1;
485	}
486
487      bp = buf;
488      while (1)
489	{
490	  c = readchar ();
491	  if (c < 0)
492	    return -1;
493	  if (c == '#')
494	    break;
495	  *bp++ = c;
496	  csum += c;
497	}
498      *bp = 0;
499
500      c1 = fromhex (readchar ());
501      c2 = fromhex (readchar ());
502
503      if (csum == (c1 << 4) + c2)
504	break;
505
506      fprintf (stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
507	       (c1 << 4) + c2, csum, buf);
508      write (remote_desc, "-", 1);
509    }
510
511  if (remote_debug)
512    {
513      fprintf (stderr, "getpkt (\"%s\");  [sending ack] \n", buf);
514      fflush (stderr);
515    }
516
517  write (remote_desc, "+", 1);
518
519  if (remote_debug)
520    {
521      fprintf (stderr, "[sent ack]\n");
522      fflush (stderr);
523    }
524
525  return bp - buf;
526}
527
528void
529write_ok (char *buf)
530{
531  buf[0] = 'O';
532  buf[1] = 'K';
533  buf[2] = '\0';
534}
535
536void
537write_enn (char *buf)
538{
539  /* Some day, we should define the meanings of the error codes... */
540  buf[0] = 'E';
541  buf[1] = '0';
542  buf[2] = '1';
543  buf[3] = '\0';
544}
545
546void
547convert_int_to_ascii (char *from, char *to, int n)
548{
549  int nib;
550  char ch;
551  while (n--)
552    {
553      ch = *from++;
554      nib = ((ch & 0xf0) >> 4) & 0x0f;
555      *to++ = tohex (nib);
556      nib = ch & 0x0f;
557      *to++ = tohex (nib);
558    }
559  *to++ = 0;
560}
561
562
563void
564convert_ascii_to_int (char *from, char *to, int n)
565{
566  int nib1, nib2;
567  while (n--)
568    {
569      nib1 = fromhex (*from++);
570      nib2 = fromhex (*from++);
571      *to++ = (((nib1 & 0x0f) << 4) & 0xf0) | (nib2 & 0x0f);
572    }
573}
574
575static char *
576outreg (int regno, char *buf)
577{
578  if ((regno >> 12) != 0)
579    *buf++ = tohex ((regno >> 12) & 0xf);
580  if ((regno >> 8) != 0)
581    *buf++ = tohex ((regno >> 8) & 0xf);
582  *buf++ = tohex ((regno >> 4) & 0xf);
583  *buf++ = tohex (regno & 0xf);
584  *buf++ = ':';
585  collect_register_as_string (regno, buf);
586  buf += 2 * register_size (regno);
587  *buf++ = ';';
588
589  return buf;
590}
591
592void
593new_thread_notify (int id)
594{
595  char own_buf[256];
596
597  /* The `n' response is not yet part of the remote protocol.  Do nothing.  */
598  if (1)
599    return;
600
601  if (server_waiting == 0)
602    return;
603
604  sprintf (own_buf, "n%x", id);
605  disable_async_io ();
606  putpkt (own_buf);
607  enable_async_io ();
608}
609
610void
611dead_thread_notify (int id)
612{
613  char own_buf[256];
614
615  /* The `x' response is not yet part of the remote protocol.  Do nothing.  */
616  if (1)
617    return;
618
619  sprintf (own_buf, "x%x", id);
620  disable_async_io ();
621  putpkt (own_buf);
622  enable_async_io ();
623}
624
625void
626prepare_resume_reply (char *buf, char status, unsigned char signo)
627{
628  int nib, sig;
629
630  *buf++ = status;
631
632  sig = (int)target_signal_from_host (signo);
633
634  nib = ((sig & 0xf0) >> 4);
635  *buf++ = tohex (nib);
636  nib = sig & 0x0f;
637  *buf++ = tohex (nib);
638
639  if (status == 'T')
640    {
641      const char **regp = gdbserver_expedite_regs;
642      while (*regp)
643	{
644	  buf = outreg (find_regno (*regp), buf);
645	  regp ++;
646	}
647
648      /* Formerly, if the debugger had not used any thread features we would not
649	 burden it with a thread status response.  This was for the benefit of
650	 GDB 4.13 and older.  However, in recent GDB versions the check
651	 (``if (cont_thread != 0)'') does not have the desired effect because of
652	 sillyness in the way that the remote protocol handles specifying a thread.
653	 Since thread support relies on qSymbol support anyway, assume GDB can handle
654	 threads.  */
655
656      if (using_threads)
657	{
658	  /* FIXME right place to set this? */
659	  thread_from_wait = ((struct inferior_list_entry *)current_inferior)->id;
660	  if (debug_threads)
661	    fprintf (stderr, "Writing resume reply for %d\n\n", thread_from_wait);
662	  /* This if (1) ought to be unnecessary.  But remote_wait in GDB
663	     will claim this event belongs to inferior_ptid if we do not
664	     specify a thread, and there's no way for gdbserver to know
665	     what inferior_ptid is.  */
666	  if (1 || old_thread_from_wait != thread_from_wait)
667	    {
668	      general_thread = thread_from_wait;
669	      sprintf (buf, "thread:%x;", thread_from_wait);
670	      buf += strlen (buf);
671	      old_thread_from_wait = thread_from_wait;
672	    }
673	}
674    }
675  /* For W and X, we're done.  */
676  *buf++ = 0;
677}
678
679void
680decode_m_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr)
681{
682  int i = 0, j = 0;
683  char ch;
684  *mem_addr_ptr = *len_ptr = 0;
685
686  while ((ch = from[i++]) != ',')
687    {
688      *mem_addr_ptr = *mem_addr_ptr << 4;
689      *mem_addr_ptr |= fromhex (ch) & 0x0f;
690    }
691
692  for (j = 0; j < 4; j++)
693    {
694      if ((ch = from[i++]) == 0)
695	break;
696      *len_ptr = *len_ptr << 4;
697      *len_ptr |= fromhex (ch) & 0x0f;
698    }
699}
700
701void
702decode_M_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr,
703		 char *to)
704{
705  int i = 0;
706  char ch;
707  *mem_addr_ptr = *len_ptr = 0;
708
709  while ((ch = from[i++]) != ',')
710    {
711      *mem_addr_ptr = *mem_addr_ptr << 4;
712      *mem_addr_ptr |= fromhex (ch) & 0x0f;
713    }
714
715  while ((ch = from[i++]) != ':')
716    {
717      *len_ptr = *len_ptr << 4;
718      *len_ptr |= fromhex (ch) & 0x0f;
719    }
720
721  convert_ascii_to_int (&from[i++], to, *len_ptr);
722}
723
724/* Ask GDB for the address of NAME, and return it in ADDRP if found.
725   Returns 1 if the symbol is found, 0 if it is not, -1 on error.  */
726
727int
728look_up_one_symbol (const char *name, CORE_ADDR *addrp)
729{
730  char own_buf[266], *p, *q;
731  int len;
732  struct sym_cache *sym;
733
734  /* Check the cache first.  */
735  for (sym = symbol_cache; sym; sym = sym->next)
736    if (strcmp (name, sym->name) == 0)
737      {
738	*addrp = sym->addr;
739	return 1;
740      }
741
742  /* Send the request.  */
743  strcpy (own_buf, "qSymbol:");
744  hexify (own_buf + strlen ("qSymbol:"), name, strlen (name));
745  if (putpkt (own_buf) < 0)
746    return -1;
747
748  /* FIXME:  Eventually add buffer overflow checking (to getpkt?)  */
749  len = getpkt (own_buf);
750  if (len < 0)
751    return -1;
752
753  if (strncmp (own_buf, "qSymbol:", strlen ("qSymbol:")) != 0)
754    {
755      /* Malformed response.  */
756      if (remote_debug)
757	{
758	  fprintf (stderr, "Malformed response to qSymbol, ignoring.\n");
759	  fflush (stderr);
760	}
761
762      return -1;
763    }
764
765  p = own_buf + strlen ("qSymbol:");
766  q = p;
767  while (*q && *q != ':')
768    q++;
769
770  /* Make sure we found a value for the symbol.  */
771  if (p == q || *q == '\0')
772    return 0;
773
774  decode_address (addrp, p, q - p);
775
776  /* Save the symbol in our cache.  */
777  sym = malloc (sizeof (*sym));
778  sym->name = strdup (name);
779  sym->addr = *addrp;
780  sym->next = symbol_cache;
781  symbol_cache = sym;
782
783  return 1;
784}
785