replace hexify with bin2hex
[external/binutils.git] / gdb / gdbserver / remote-utils.c
1 /* Remote utility routines for the remote server for GDB.
2    Copyright (C) 1986-2014 Free Software Foundation, Inc.
3
4    This file is part of GDB.
5
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.
10
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.
15
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/>.  */
18
19 #include "server.h"
20 #include "terminal.h"
21 #include "target.h"
22 #include "gdbthread.h"
23 #include "tdesc.h"
24 #include "dll.h"
25 #include "rsp-low.h"
26
27 #include <stdio.h>
28 #include <string.h>
29 #if HAVE_SYS_IOCTL_H
30 #include <sys/ioctl.h>
31 #endif
32 #if HAVE_SYS_FILE_H
33 #include <sys/file.h>
34 #endif
35 #if HAVE_NETINET_IN_H
36 #include <netinet/in.h>
37 #endif
38 #if HAVE_SYS_SOCKET_H
39 #include <sys/socket.h>
40 #endif
41 #if HAVE_NETDB_H
42 #include <netdb.h>
43 #endif
44 #if HAVE_NETINET_TCP_H
45 #include <netinet/tcp.h>
46 #endif
47 #if HAVE_SYS_IOCTL_H
48 #include <sys/ioctl.h>
49 #endif
50 #if HAVE_SIGNAL_H
51 #include <signal.h>
52 #endif
53 #if HAVE_FCNTL_H
54 #include <fcntl.h>
55 #endif
56 #include <sys/time.h>
57 #include <unistd.h>
58 #if HAVE_ARPA_INET_H
59 #include <arpa/inet.h>
60 #endif
61 #include <sys/stat.h>
62 #if HAVE_ERRNO_H
63 #include <errno.h>
64 #endif
65
66 #if USE_WIN32API
67 #include <winsock2.h>
68 #endif
69
70 #if __QNX__
71 #include <sys/iomgr.h>
72 #endif /* __QNX__ */
73
74 #ifndef HAVE_SOCKLEN_T
75 typedef int socklen_t;
76 #endif
77
78 #ifndef IN_PROCESS_AGENT
79
80 #if USE_WIN32API
81 # define INVALID_DESCRIPTOR INVALID_SOCKET
82 #else
83 # define INVALID_DESCRIPTOR -1
84 #endif
85
86 /* Extra value for readchar_callback.  */
87 enum {
88   /* The callback is currently not scheduled.  */
89   NOT_SCHEDULED = -1
90 };
91
92 /* Status of the readchar callback.
93    Either NOT_SCHEDULED or the callback id.  */
94 static int readchar_callback = NOT_SCHEDULED;
95
96 static int readchar (void);
97 static void reset_readchar (void);
98 static void reschedule (void);
99
100 /* A cache entry for a successfully looked-up symbol.  */
101 struct sym_cache
102 {
103   char *name;
104   CORE_ADDR addr;
105   struct sym_cache *next;
106 };
107
108 int remote_debug = 0;
109 struct ui_file *gdb_stdlog;
110
111 static int remote_is_stdio = 0;
112
113 static gdb_fildes_t remote_desc = INVALID_DESCRIPTOR;
114 static gdb_fildes_t listen_desc = INVALID_DESCRIPTOR;
115
116 /* FIXME headerize? */
117 extern int using_threads;
118 extern int debug_threads;
119
120 /* If true, then GDB has requested noack mode.  */
121 int noack_mode = 0;
122 /* If true, then we tell GDB to use noack mode by default.  */
123 int transport_is_reliable = 0;
124
125 #ifdef USE_WIN32API
126 # define read(fd, buf, len) recv (fd, (char *) buf, len, 0)
127 # define write(fd, buf, len) send (fd, (char *) buf, len, 0)
128 #endif
129
130 int
131 gdb_connected (void)
132 {
133   return remote_desc != INVALID_DESCRIPTOR;
134 }
135
136 /* Return true if the remote connection is over stdio.  */
137
138 int
139 remote_connection_is_stdio (void)
140 {
141   return remote_is_stdio;
142 }
143
144 static void
145 enable_async_notification (int fd)
146 {
147 #if defined(F_SETFL) && defined (FASYNC)
148   int save_fcntl_flags;
149
150   save_fcntl_flags = fcntl (fd, F_GETFL, 0);
151   fcntl (fd, F_SETFL, save_fcntl_flags | FASYNC);
152 #if defined (F_SETOWN)
153   fcntl (fd, F_SETOWN, getpid ());
154 #endif
155 #endif
156 }
157
158 static int
159 handle_accept_event (int err, gdb_client_data client_data)
160 {
161   struct sockaddr_in sockaddr;
162   socklen_t tmp;
163
164   if (debug_threads)
165     debug_printf ("handling possible accept event\n");
166
167   tmp = sizeof (sockaddr);
168   remote_desc = accept (listen_desc, (struct sockaddr *) &sockaddr, &tmp);
169   if (remote_desc == -1)
170     perror_with_name ("Accept failed");
171
172   /* Enable TCP keep alive process. */
173   tmp = 1;
174   setsockopt (remote_desc, SOL_SOCKET, SO_KEEPALIVE,
175               (char *) &tmp, sizeof (tmp));
176
177   /* Tell TCP not to delay small packets.  This greatly speeds up
178      interactive response. */
179   tmp = 1;
180   setsockopt (remote_desc, IPPROTO_TCP, TCP_NODELAY,
181               (char *) &tmp, sizeof (tmp));
182
183 #ifndef USE_WIN32API
184   signal (SIGPIPE, SIG_IGN);    /* If we don't do this, then gdbserver simply
185                                    exits when the remote side dies.  */
186 #endif
187
188   if (run_once)
189     {
190 #ifndef USE_WIN32API
191       close (listen_desc);              /* No longer need this */
192 #else
193       closesocket (listen_desc);        /* No longer need this */
194 #endif
195     }
196
197   /* Even if !RUN_ONCE no longer notice new connections.  Still keep the
198      descriptor open for add_file_handler to wait for a new connection.  */
199   delete_file_handler (listen_desc);
200
201   /* Convert IP address to string.  */
202   fprintf (stderr, "Remote debugging from host %s\n",
203            inet_ntoa (sockaddr.sin_addr));
204
205   enable_async_notification (remote_desc);
206
207   /* Register the event loop handler.  */
208   add_file_handler (remote_desc, handle_serial_event, NULL);
209
210   /* We have a new GDB connection now.  If we were disconnected
211      tracing, there's a window where the target could report a stop
212      event to the event loop, and since we have a connection now, we'd
213      try to send vStopped notifications to GDB.  But, don't do that
214      until GDB as selected all-stop/non-stop, and has queried the
215      threads' status ('?').  */
216   target_async (0);
217
218   return 0;
219 }
220
221 /* Prepare for a later connection to a remote debugger.
222    NAME is the filename used for communication.  */
223
224 void
225 remote_prepare (char *name)
226 {
227   char *port_str;
228 #ifdef USE_WIN32API
229   static int winsock_initialized;
230 #endif
231   int port;
232   struct sockaddr_in sockaddr;
233   socklen_t tmp;
234   char *port_end;
235
236   remote_is_stdio = 0;
237   if (strcmp (name, STDIO_CONNECTION_NAME) == 0)
238     {
239       /* We need to record fact that we're using stdio sooner than the
240          call to remote_open so start_inferior knows the connection is
241          via stdio.  */
242       remote_is_stdio = 1;
243       transport_is_reliable = 1;
244       return;
245     }
246
247   port_str = strchr (name, ':');
248   if (port_str == NULL)
249     {
250       transport_is_reliable = 0;
251       return;
252     }
253
254   port = strtoul (port_str + 1, &port_end, 10);
255   if (port_str[1] == '\0' || *port_end != '\0')
256     fatal ("Bad port argument: %s", name);
257
258 #ifdef USE_WIN32API
259   if (!winsock_initialized)
260     {
261       WSADATA wsad;
262
263       WSAStartup (MAKEWORD (1, 0), &wsad);
264       winsock_initialized = 1;
265     }
266 #endif
267
268   listen_desc = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
269   if (listen_desc == -1)
270     perror_with_name ("Can't open socket");
271
272   /* Allow rapid reuse of this port. */
273   tmp = 1;
274   setsockopt (listen_desc, SOL_SOCKET, SO_REUSEADDR, (char *) &tmp,
275               sizeof (tmp));
276
277   sockaddr.sin_family = PF_INET;
278   sockaddr.sin_port = htons (port);
279   sockaddr.sin_addr.s_addr = INADDR_ANY;
280
281   if (bind (listen_desc, (struct sockaddr *) &sockaddr, sizeof (sockaddr))
282       || listen (listen_desc, 1))
283     perror_with_name ("Can't bind address");
284
285   transport_is_reliable = 1;
286 }
287
288 /* Open a connection to a remote debugger.
289    NAME is the filename used for communication.  */
290
291 void
292 remote_open (char *name)
293 {
294   char *port_str;
295
296   port_str = strchr (name, ':');
297 #ifdef USE_WIN32API
298   if (port_str == NULL)
299     error ("Only <host>:<port> is supported on this platform.");
300 #endif
301
302   if (strcmp (name, STDIO_CONNECTION_NAME) == 0)
303     {
304       fprintf (stderr, "Remote debugging using stdio\n");
305
306       /* Use stdin as the handle of the connection.
307          We only select on reads, for example.  */
308       remote_desc = fileno (stdin);
309
310       enable_async_notification (remote_desc);
311
312       /* Register the event loop handler.  */
313       add_file_handler (remote_desc, handle_serial_event, NULL);
314     }
315 #ifndef USE_WIN32API
316   else if (port_str == NULL)
317     {
318       struct stat statbuf;
319
320       if (stat (name, &statbuf) == 0
321           && (S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode)))
322         remote_desc = open (name, O_RDWR);
323       else
324         {
325           errno = EINVAL;
326           remote_desc = -1;
327         }
328
329       if (remote_desc < 0)
330         perror_with_name ("Could not open remote device");
331
332 #ifdef HAVE_TERMIOS
333       {
334         struct termios termios;
335         tcgetattr (remote_desc, &termios);
336
337         termios.c_iflag = 0;
338         termios.c_oflag = 0;
339         termios.c_lflag = 0;
340         termios.c_cflag &= ~(CSIZE | PARENB);
341         termios.c_cflag |= CLOCAL | CS8;
342         termios.c_cc[VMIN] = 1;
343         termios.c_cc[VTIME] = 0;
344
345         tcsetattr (remote_desc, TCSANOW, &termios);
346       }
347 #endif
348
349 #ifdef HAVE_TERMIO
350       {
351         struct termio termio;
352         ioctl (remote_desc, TCGETA, &termio);
353
354         termio.c_iflag = 0;
355         termio.c_oflag = 0;
356         termio.c_lflag = 0;
357         termio.c_cflag &= ~(CSIZE | PARENB);
358         termio.c_cflag |= CLOCAL | CS8;
359         termio.c_cc[VMIN] = 1;
360         termio.c_cc[VTIME] = 0;
361
362         ioctl (remote_desc, TCSETA, &termio);
363       }
364 #endif
365
366 #ifdef HAVE_SGTTY
367       {
368         struct sgttyb sg;
369
370         ioctl (remote_desc, TIOCGETP, &sg);
371         sg.sg_flags = RAW;
372         ioctl (remote_desc, TIOCSETP, &sg);
373       }
374 #endif
375
376       fprintf (stderr, "Remote debugging using %s\n", name);
377
378       enable_async_notification (remote_desc);
379
380       /* Register the event loop handler.  */
381       add_file_handler (remote_desc, handle_serial_event, NULL);
382     }
383 #endif /* USE_WIN32API */
384   else
385     {
386       int port;
387       socklen_t len;
388       struct sockaddr_in sockaddr;
389
390       len = sizeof (sockaddr);
391       if (getsockname (listen_desc,
392                        (struct sockaddr *) &sockaddr, &len) < 0
393           || len < sizeof (sockaddr))
394         perror_with_name ("Can't determine port");
395       port = ntohs (sockaddr.sin_port);
396
397       fprintf (stderr, "Listening on port %d\n", port);
398       fflush (stderr);
399
400       /* Register the event loop handler.  */
401       add_file_handler (listen_desc, handle_accept_event, NULL);
402     }
403 }
404
405 void
406 remote_close (void)
407 {
408   delete_file_handler (remote_desc);
409
410 #ifdef USE_WIN32API
411   closesocket (remote_desc);
412 #else
413   if (! remote_connection_is_stdio ())
414     close (remote_desc);
415 #endif
416   remote_desc = INVALID_DESCRIPTOR;
417
418   reset_readchar ();
419 }
420
421 #endif
422
423 #ifndef IN_PROCESS_AGENT
424
425 void
426 decode_address (CORE_ADDR *addrp, const char *start, int len)
427 {
428   CORE_ADDR addr;
429   char ch;
430   int i;
431
432   addr = 0;
433   for (i = 0; i < len; i++)
434     {
435       ch = start[i];
436       addr = addr << 4;
437       addr = addr | (fromhex (ch) & 0x0f);
438     }
439   *addrp = addr;
440 }
441
442 const char *
443 decode_address_to_semicolon (CORE_ADDR *addrp, const char *start)
444 {
445   const char *end;
446
447   end = start;
448   while (*end != '\0' && *end != ';')
449     end++;
450
451   decode_address (addrp, start, end - start);
452
453   if (*end == ';')
454     end++;
455   return end;
456 }
457
458 #endif
459
460 #ifndef IN_PROCESS_AGENT
461
462 /* Look for a sequence of characters which can be run-length encoded.
463    If there are any, update *CSUM and *P.  Otherwise, output the
464    single character.  Return the number of characters consumed.  */
465
466 static int
467 try_rle (char *buf, int remaining, unsigned char *csum, char **p)
468 {
469   int n;
470
471   /* Always output the character.  */
472   *csum += buf[0];
473   *(*p)++ = buf[0];
474
475   /* Don't go past '~'.  */
476   if (remaining > 97)
477     remaining = 97;
478
479   for (n = 1; n < remaining; n++)
480     if (buf[n] != buf[0])
481       break;
482
483   /* N is the index of the first character not the same as buf[0].
484      buf[0] is counted twice, so by decrementing N, we get the number
485      of characters the RLE sequence will replace.  */
486   n--;
487
488   if (n < 3)
489     return 1;
490
491   /* Skip the frame characters.  The manual says to skip '+' and '-'
492      also, but there's no reason to.  Unfortunately these two unusable
493      characters double the encoded length of a four byte zero
494      value.  */
495   while (n + 29 == '$' || n + 29 == '#')
496     n--;
497
498   *csum += '*';
499   *(*p)++ = '*';
500   *csum += n + 29;
501   *(*p)++ = n + 29;
502
503   return n + 1;
504 }
505
506 #endif
507
508 #ifndef IN_PROCESS_AGENT
509
510 /* Write a PTID to BUF.  Returns BUF+CHARACTERS_WRITTEN.  */
511
512 char *
513 write_ptid (char *buf, ptid_t ptid)
514 {
515   int pid, tid;
516
517   if (multi_process)
518     {
519       pid = ptid_get_pid (ptid);
520       if (pid < 0)
521         buf += sprintf (buf, "p-%x.", -pid);
522       else
523         buf += sprintf (buf, "p%x.", pid);
524     }
525   tid = ptid_get_lwp (ptid);
526   if (tid < 0)
527     buf += sprintf (buf, "-%x", -tid);
528   else
529     buf += sprintf (buf, "%x", tid);
530
531   return buf;
532 }
533
534 ULONGEST
535 hex_or_minus_one (char *buf, char **obuf)
536 {
537   ULONGEST ret;
538
539   if (strncmp (buf, "-1", 2) == 0)
540     {
541       ret = (ULONGEST) -1;
542       buf += 2;
543     }
544   else
545     buf = unpack_varlen_hex (buf, &ret);
546
547   if (obuf)
548     *obuf = buf;
549
550   return ret;
551 }
552
553 /* Extract a PTID from BUF.  If non-null, OBUF is set to the to one
554    passed the last parsed char.  Returns null_ptid on error.  */
555 ptid_t
556 read_ptid (char *buf, char **obuf)
557 {
558   char *p = buf;
559   char *pp;
560   ULONGEST pid = 0, tid = 0;
561
562   if (*p == 'p')
563     {
564       /* Multi-process ptid.  */
565       pp = unpack_varlen_hex (p + 1, &pid);
566       if (*pp != '.')
567         error ("invalid remote ptid: %s\n", p);
568
569       p = pp + 1;
570
571       tid = hex_or_minus_one (p, &pp);
572
573       if (obuf)
574         *obuf = pp;
575       return ptid_build (pid, tid, 0);
576     }
577
578   /* No multi-process.  Just a tid.  */
579   tid = hex_or_minus_one (p, &pp);
580
581   /* Since the stub is not sending a process id, then default to
582      what's in the current inferior.  */
583   pid = ptid_get_pid (current_ptid);
584
585   if (obuf)
586     *obuf = pp;
587   return ptid_build (pid, tid, 0);
588 }
589
590 /* Write COUNT bytes in BUF to the client.
591    The result is the number of bytes written or -1 if error.
592    This may return less than COUNT.  */
593
594 static int
595 write_prim (const void *buf, int count)
596 {
597   if (remote_connection_is_stdio ())
598     return write (fileno (stdout), buf, count);
599   else
600     return write (remote_desc, buf, count);
601 }
602
603 /* Read COUNT bytes from the client and store in BUF.
604    The result is the number of bytes read or -1 if error.
605    This may return less than COUNT.  */
606
607 static int
608 read_prim (void *buf, int count)
609 {
610   if (remote_connection_is_stdio ())
611     return read (fileno (stdin), buf, count);
612   else
613     return read (remote_desc, buf, count);
614 }
615
616 /* Send a packet to the remote machine, with error checking.
617    The data of the packet is in BUF, and the length of the
618    packet is in CNT.  Returns >= 0 on success, -1 otherwise.  */
619
620 static int
621 putpkt_binary_1 (char *buf, int cnt, int is_notif)
622 {
623   int i;
624   unsigned char csum = 0;
625   char *buf2;
626   char *p;
627   int cc;
628
629   buf2 = xmalloc (strlen ("$") + cnt + strlen ("#nn") + 1);
630
631   /* Copy the packet into buffer BUF2, encapsulating it
632      and giving it a checksum.  */
633
634   p = buf2;
635   if (is_notif)
636     *p++ = '%';
637   else
638     *p++ = '$';
639
640   for (i = 0; i < cnt;)
641     i += try_rle (buf + i, cnt - i, &csum, &p);
642
643   *p++ = '#';
644   *p++ = tohex ((csum >> 4) & 0xf);
645   *p++ = tohex (csum & 0xf);
646
647   *p = '\0';
648
649   /* Send it over and over until we get a positive ack.  */
650
651   do
652     {
653       if (write_prim (buf2, p - buf2) != p - buf2)
654         {
655           perror ("putpkt(write)");
656           free (buf2);
657           return -1;
658         }
659
660       if (noack_mode || is_notif)
661         {
662           /* Don't expect an ack then.  */
663           if (remote_debug)
664             {
665               if (is_notif)
666                 fprintf (stderr, "putpkt (\"%s\"); [notif]\n", buf2);
667               else
668                 fprintf (stderr, "putpkt (\"%s\"); [noack mode]\n", buf2);
669               fflush (stderr);
670             }
671           break;
672         }
673
674       if (remote_debug)
675         {
676           fprintf (stderr, "putpkt (\"%s\"); [looking for ack]\n", buf2);
677           fflush (stderr);
678         }
679
680       cc = readchar ();
681
682       if (cc < 0)
683         {
684           free (buf2);
685           return -1;
686         }
687
688       if (remote_debug)
689         {
690           fprintf (stderr, "[received '%c' (0x%x)]\n", cc, cc);
691           fflush (stderr);
692         }
693
694       /* Check for an input interrupt while we're here.  */
695       if (cc == '\003' && current_inferior != NULL)
696         (*the_target->request_interrupt) ();
697     }
698   while (cc != '+');
699
700   free (buf2);
701   return 1;                     /* Success! */
702 }
703
704 int
705 putpkt_binary (char *buf, int cnt)
706 {
707   return putpkt_binary_1 (buf, cnt, 0);
708 }
709
710 /* Send a packet to the remote machine, with error checking.  The data
711    of the packet is in BUF, and the packet should be a NUL-terminated
712    string.  Returns >= 0 on success, -1 otherwise.  */
713
714 int
715 putpkt (char *buf)
716 {
717   return putpkt_binary (buf, strlen (buf));
718 }
719
720 int
721 putpkt_notif (char *buf)
722 {
723   return putpkt_binary_1 (buf, strlen (buf), 1);
724 }
725
726 /* Come here when we get an input interrupt from the remote side.  This
727    interrupt should only be active while we are waiting for the child to do
728    something.  Thus this assumes readchar:bufcnt is 0.
729    About the only thing that should come through is a ^C, which
730    will cause us to request child interruption.  */
731
732 static void
733 input_interrupt (int unused)
734 {
735   fd_set readset;
736   struct timeval immediate = { 0, 0 };
737
738   /* Protect against spurious interrupts.  This has been observed to
739      be a problem under NetBSD 1.4 and 1.5.  */
740
741   FD_ZERO (&readset);
742   FD_SET (remote_desc, &readset);
743   if (select (remote_desc + 1, &readset, 0, 0, &immediate) > 0)
744     {
745       int cc;
746       char c = 0;
747
748       cc = read_prim (&c, 1);
749
750       if (cc != 1 || c != '\003' || current_inferior == NULL)
751         {
752           fprintf (stderr, "input_interrupt, count = %d c = %d ('%c')\n",
753                    cc, c, c);
754           return;
755         }
756
757       (*the_target->request_interrupt) ();
758     }
759 }
760
761 /* Check if the remote side sent us an interrupt request (^C).  */
762 void
763 check_remote_input_interrupt_request (void)
764 {
765   /* This function may be called before establishing communications,
766      therefore we need to validate the remote descriptor.  */
767
768   if (remote_desc == INVALID_DESCRIPTOR)
769     return;
770
771   input_interrupt (0);
772 }
773
774 /* Asynchronous I/O support.  SIGIO must be enabled when waiting, in order to
775    accept Control-C from the client, and must be disabled when talking to
776    the client.  */
777
778 static void
779 unblock_async_io (void)
780 {
781 #ifndef USE_WIN32API
782   sigset_t sigio_set;
783
784   sigemptyset (&sigio_set);
785   sigaddset (&sigio_set, SIGIO);
786   sigprocmask (SIG_UNBLOCK, &sigio_set, NULL);
787 #endif
788 }
789
790 #ifdef __QNX__
791 static void
792 nto_comctrl (int enable)
793 {
794   struct sigevent event;
795
796   if (enable)
797     {
798       event.sigev_notify = SIGEV_SIGNAL_THREAD;
799       event.sigev_signo = SIGIO;
800       event.sigev_code = 0;
801       event.sigev_value.sival_ptr = NULL;
802       event.sigev_priority = -1;
803       ionotify (remote_desc, _NOTIFY_ACTION_POLLARM, _NOTIFY_COND_INPUT,
804                 &event);
805     }
806   else
807     ionotify (remote_desc, _NOTIFY_ACTION_POLL, _NOTIFY_COND_INPUT, NULL);
808 }
809 #endif /* __QNX__ */
810
811
812 /* Current state of asynchronous I/O.  */
813 static int async_io_enabled;
814
815 /* Enable asynchronous I/O.  */
816 void
817 enable_async_io (void)
818 {
819   if (async_io_enabled)
820     return;
821
822 #ifndef USE_WIN32API
823   signal (SIGIO, input_interrupt);
824 #endif
825   async_io_enabled = 1;
826 #ifdef __QNX__
827   nto_comctrl (1);
828 #endif /* __QNX__ */
829 }
830
831 /* Disable asynchronous I/O.  */
832 void
833 disable_async_io (void)
834 {
835   if (!async_io_enabled)
836     return;
837
838 #ifndef USE_WIN32API
839   signal (SIGIO, SIG_IGN);
840 #endif
841   async_io_enabled = 0;
842 #ifdef __QNX__
843   nto_comctrl (0);
844 #endif /* __QNX__ */
845
846 }
847
848 void
849 initialize_async_io (void)
850 {
851   /* Make sure that async I/O starts disabled.  */
852   async_io_enabled = 1;
853   disable_async_io ();
854
855   /* Make sure the signal is unblocked.  */
856   unblock_async_io ();
857 }
858
859 /* Internal buffer used by readchar.
860    These are global to readchar because reschedule_remote needs to be
861    able to tell whether the buffer is empty.  */
862
863 static unsigned char readchar_buf[BUFSIZ];
864 static int readchar_bufcnt = 0;
865 static unsigned char *readchar_bufp;
866
867 /* Returns next char from remote GDB.  -1 if error.  */
868
869 static int
870 readchar (void)
871 {
872   int ch;
873
874   if (readchar_bufcnt == 0)
875     {
876       readchar_bufcnt = read_prim (readchar_buf, sizeof (readchar_buf));
877
878       if (readchar_bufcnt <= 0)
879         {
880           if (readchar_bufcnt == 0)
881             fprintf (stderr, "readchar: Got EOF\n");
882           else
883             perror ("readchar");
884
885           return -1;
886         }
887
888       readchar_bufp = readchar_buf;
889     }
890
891   readchar_bufcnt--;
892   ch = *readchar_bufp++;
893   reschedule ();
894   return ch;
895 }
896
897 /* Reset the readchar state machine.  */
898
899 static void
900 reset_readchar (void)
901 {
902   readchar_bufcnt = 0;
903   if (readchar_callback != NOT_SCHEDULED)
904     {
905       delete_callback_event (readchar_callback);
906       readchar_callback = NOT_SCHEDULED;
907     }
908 }
909
910 /* Process remaining data in readchar_buf.  */
911
912 static int
913 process_remaining (void *context)
914 {
915   int res;
916
917   /* This is a one-shot event.  */
918   readchar_callback = NOT_SCHEDULED;
919
920   if (readchar_bufcnt > 0)
921     res = handle_serial_event (0, NULL);
922   else
923     res = 0;
924
925   return res;
926 }
927
928 /* If there is still data in the buffer, queue another event to process it,
929    we can't sleep in select yet.  */
930
931 static void
932 reschedule (void)
933 {
934   if (readchar_bufcnt > 0 && readchar_callback == NOT_SCHEDULED)
935     readchar_callback = append_callback_event (process_remaining, NULL);
936 }
937
938 /* Read a packet from the remote machine, with error checking,
939    and store it in BUF.  Returns length of packet, or negative if error. */
940
941 int
942 getpkt (char *buf)
943 {
944   char *bp;
945   unsigned char csum, c1, c2;
946   int c;
947
948   while (1)
949     {
950       csum = 0;
951
952       while (1)
953         {
954           c = readchar ();
955           if (c == '$')
956             break;
957           if (remote_debug)
958             {
959               fprintf (stderr, "[getpkt: discarding char '%c']\n", c);
960               fflush (stderr);
961             }
962
963           if (c < 0)
964             return -1;
965         }
966
967       bp = buf;
968       while (1)
969         {
970           c = readchar ();
971           if (c < 0)
972             return -1;
973           if (c == '#')
974             break;
975           *bp++ = c;
976           csum += c;
977         }
978       *bp = 0;
979
980       c1 = fromhex (readchar ());
981       c2 = fromhex (readchar ());
982
983       if (csum == (c1 << 4) + c2)
984         break;
985
986       if (noack_mode)
987         {
988           fprintf (stderr,
989                    "Bad checksum, sentsum=0x%x, csum=0x%x, "
990                    "buf=%s [no-ack-mode, Bad medium?]\n",
991                    (c1 << 4) + c2, csum, buf);
992           /* Not much we can do, GDB wasn't expecting an ack/nac.  */
993           break;
994         }
995
996       fprintf (stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
997                (c1 << 4) + c2, csum, buf);
998       if (write_prim ("-", 1) != 1)
999         return -1;
1000     }
1001
1002   if (!noack_mode)
1003     {
1004       if (remote_debug)
1005         {
1006           fprintf (stderr, "getpkt (\"%s\");  [sending ack] \n", buf);
1007           fflush (stderr);
1008         }
1009
1010       if (write_prim ("+", 1) != 1)
1011         return -1;
1012
1013       if (remote_debug)
1014         {
1015           fprintf (stderr, "[sent ack]\n");
1016           fflush (stderr);
1017         }
1018     }
1019   else
1020     {
1021       if (remote_debug)
1022         {
1023           fprintf (stderr, "getpkt (\"%s\");  [no ack sent] \n", buf);
1024           fflush (stderr);
1025         }
1026     }
1027
1028   return bp - buf;
1029 }
1030
1031 void
1032 write_ok (char *buf)
1033 {
1034   buf[0] = 'O';
1035   buf[1] = 'K';
1036   buf[2] = '\0';
1037 }
1038
1039 void
1040 write_enn (char *buf)
1041 {
1042   /* Some day, we should define the meanings of the error codes... */
1043   buf[0] = 'E';
1044   buf[1] = '0';
1045   buf[2] = '1';
1046   buf[3] = '\0';
1047 }
1048
1049 #endif
1050
1051 #ifndef IN_PROCESS_AGENT
1052
1053 static char *
1054 outreg (struct regcache *regcache, int regno, char *buf)
1055 {
1056   if ((regno >> 12) != 0)
1057     *buf++ = tohex ((regno >> 12) & 0xf);
1058   if ((regno >> 8) != 0)
1059     *buf++ = tohex ((regno >> 8) & 0xf);
1060   *buf++ = tohex ((regno >> 4) & 0xf);
1061   *buf++ = tohex (regno & 0xf);
1062   *buf++ = ':';
1063   collect_register_as_string (regcache, regno, buf);
1064   buf += 2 * register_size (regcache->tdesc, regno);
1065   *buf++ = ';';
1066
1067   return buf;
1068 }
1069
1070 void
1071 new_thread_notify (int id)
1072 {
1073   char own_buf[256];
1074
1075   /* The `n' response is not yet part of the remote protocol.  Do nothing.  */
1076   if (1)
1077     return;
1078
1079   if (server_waiting == 0)
1080     return;
1081
1082   sprintf (own_buf, "n%x", id);
1083   disable_async_io ();
1084   putpkt (own_buf);
1085   enable_async_io ();
1086 }
1087
1088 void
1089 dead_thread_notify (int id)
1090 {
1091   char own_buf[256];
1092
1093   /* The `x' response is not yet part of the remote protocol.  Do nothing.  */
1094   if (1)
1095     return;
1096
1097   sprintf (own_buf, "x%x", id);
1098   disable_async_io ();
1099   putpkt (own_buf);
1100   enable_async_io ();
1101 }
1102
1103 void
1104 prepare_resume_reply (char *buf, ptid_t ptid,
1105                       struct target_waitstatus *status)
1106 {
1107   if (debug_threads)
1108     debug_printf ("Writing resume reply for %s:%d\n",
1109                   target_pid_to_str (ptid), status->kind);
1110
1111   switch (status->kind)
1112     {
1113     case TARGET_WAITKIND_STOPPED:
1114       {
1115         struct thread_info *saved_inferior;
1116         const char **regp;
1117         struct regcache *regcache;
1118
1119         sprintf (buf, "T%02x", status->value.sig);
1120         buf += strlen (buf);
1121
1122         saved_inferior = current_inferior;
1123
1124         current_inferior = find_thread_ptid (ptid);
1125
1126         regp = current_target_desc ()->expedite_regs;
1127
1128         regcache = get_thread_regcache (current_inferior, 1);
1129
1130         if (the_target->stopped_by_watchpoint != NULL
1131             && (*the_target->stopped_by_watchpoint) ())
1132           {
1133             CORE_ADDR addr;
1134             int i;
1135
1136             strncpy (buf, "watch:", 6);
1137             buf += 6;
1138
1139             addr = (*the_target->stopped_data_address) ();
1140
1141             /* Convert each byte of the address into two hexadecimal
1142                chars.  Note that we take sizeof (void *) instead of
1143                sizeof (addr); this is to avoid sending a 64-bit
1144                address to a 32-bit GDB.  */
1145             for (i = sizeof (void *) * 2; i > 0; i--)
1146               *buf++ = tohex ((addr >> (i - 1) * 4) & 0xf);
1147             *buf++ = ';';
1148           }
1149
1150         while (*regp)
1151           {
1152             buf = outreg (regcache, find_regno (regcache->tdesc, *regp), buf);
1153             regp ++;
1154           }
1155         *buf = '\0';
1156
1157         /* Formerly, if the debugger had not used any thread features
1158            we would not burden it with a thread status response.  This
1159            was for the benefit of GDB 4.13 and older.  However, in
1160            recent GDB versions the check (``if (cont_thread != 0)'')
1161            does not have the desired effect because of sillyness in
1162            the way that the remote protocol handles specifying a
1163            thread.  Since thread support relies on qSymbol support
1164            anyway, assume GDB can handle threads.  */
1165
1166         if (using_threads && !disable_packet_Tthread)
1167           {
1168             /* This if (1) ought to be unnecessary.  But remote_wait
1169                in GDB will claim this event belongs to inferior_ptid
1170                if we do not specify a thread, and there's no way for
1171                gdbserver to know what inferior_ptid is.  */
1172             if (1 || !ptid_equal (general_thread, ptid))
1173               {
1174                 int core = -1;
1175                 /* In non-stop, don't change the general thread behind
1176                    GDB's back.  */
1177                 if (!non_stop)
1178                   general_thread = ptid;
1179                 sprintf (buf, "thread:");
1180                 buf += strlen (buf);
1181                 buf = write_ptid (buf, ptid);
1182                 strcat (buf, ";");
1183                 buf += strlen (buf);
1184
1185                 core = target_core_of_thread (ptid);
1186
1187                 if (core != -1)
1188                   {
1189                     sprintf (buf, "core:");
1190                     buf += strlen (buf);
1191                     sprintf (buf, "%x", core);
1192                     strcat (buf, ";");
1193                     buf += strlen (buf);
1194                   }
1195               }
1196           }
1197
1198         if (dlls_changed)
1199           {
1200             strcpy (buf, "library:;");
1201             buf += strlen (buf);
1202             dlls_changed = 0;
1203           }
1204
1205         current_inferior = saved_inferior;
1206       }
1207       break;
1208     case TARGET_WAITKIND_EXITED:
1209       if (multi_process)
1210         sprintf (buf, "W%x;process:%x",
1211                  status->value.integer, ptid_get_pid (ptid));
1212       else
1213         sprintf (buf, "W%02x", status->value.integer);
1214       break;
1215     case TARGET_WAITKIND_SIGNALLED:
1216       if (multi_process)
1217         sprintf (buf, "X%x;process:%x",
1218                  status->value.sig, ptid_get_pid (ptid));
1219       else
1220         sprintf (buf, "X%02x", status->value.sig);
1221       break;
1222     default:
1223       error ("unhandled waitkind");
1224       break;
1225     }
1226 }
1227
1228 void
1229 decode_m_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr)
1230 {
1231   int i = 0, j = 0;
1232   char ch;
1233   *mem_addr_ptr = *len_ptr = 0;
1234
1235   while ((ch = from[i++]) != ',')
1236     {
1237       *mem_addr_ptr = *mem_addr_ptr << 4;
1238       *mem_addr_ptr |= fromhex (ch) & 0x0f;
1239     }
1240
1241   for (j = 0; j < 4; j++)
1242     {
1243       if ((ch = from[i++]) == 0)
1244         break;
1245       *len_ptr = *len_ptr << 4;
1246       *len_ptr |= fromhex (ch) & 0x0f;
1247     }
1248 }
1249
1250 void
1251 decode_M_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr,
1252                  unsigned char **to_p)
1253 {
1254   int i = 0;
1255   char ch;
1256   *mem_addr_ptr = *len_ptr = 0;
1257
1258   while ((ch = from[i++]) != ',')
1259     {
1260       *mem_addr_ptr = *mem_addr_ptr << 4;
1261       *mem_addr_ptr |= fromhex (ch) & 0x0f;
1262     }
1263
1264   while ((ch = from[i++]) != ':')
1265     {
1266       *len_ptr = *len_ptr << 4;
1267       *len_ptr |= fromhex (ch) & 0x0f;
1268     }
1269
1270   if (*to_p == NULL)
1271     *to_p = xmalloc (*len_ptr);
1272
1273   convert_ascii_to_int (&from[i++], *to_p, *len_ptr);
1274 }
1275
1276 int
1277 decode_X_packet (char *from, int packet_len, CORE_ADDR *mem_addr_ptr,
1278                  unsigned int *len_ptr, unsigned char **to_p)
1279 {
1280   int i = 0;
1281   char ch;
1282   *mem_addr_ptr = *len_ptr = 0;
1283
1284   while ((ch = from[i++]) != ',')
1285     {
1286       *mem_addr_ptr = *mem_addr_ptr << 4;
1287       *mem_addr_ptr |= fromhex (ch) & 0x0f;
1288     }
1289
1290   while ((ch = from[i++]) != ':')
1291     {
1292       *len_ptr = *len_ptr << 4;
1293       *len_ptr |= fromhex (ch) & 0x0f;
1294     }
1295
1296   if (*to_p == NULL)
1297     *to_p = xmalloc (*len_ptr);
1298
1299   if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len - i,
1300                              *to_p, *len_ptr) != *len_ptr)
1301     return -1;
1302
1303   return 0;
1304 }
1305
1306 /* Decode a qXfer write request.  */
1307
1308 int
1309 decode_xfer_write (char *buf, int packet_len, CORE_ADDR *offset,
1310                    unsigned int *len, unsigned char *data)
1311 {
1312   char ch;
1313   char *b = buf;
1314
1315   /* Extract the offset.  */
1316   *offset = 0;
1317   while ((ch = *buf++) != ':')
1318     {
1319       *offset = *offset << 4;
1320       *offset |= fromhex (ch) & 0x0f;
1321     }
1322
1323   /* Get encoded data.  */
1324   packet_len -= buf - b;
1325   *len = remote_unescape_input ((const gdb_byte *) buf, packet_len,
1326                                 data, packet_len);
1327   return 0;
1328 }
1329
1330 /* Decode the parameters of a qSearch:memory packet.  */
1331
1332 int
1333 decode_search_memory_packet (const char *buf, int packet_len,
1334                              CORE_ADDR *start_addrp,
1335                              CORE_ADDR *search_space_lenp,
1336                              gdb_byte *pattern, unsigned int *pattern_lenp)
1337 {
1338   const char *p = buf;
1339
1340   p = decode_address_to_semicolon (start_addrp, p);
1341   p = decode_address_to_semicolon (search_space_lenp, p);
1342   packet_len -= p - buf;
1343   *pattern_lenp = remote_unescape_input ((const gdb_byte *) p, packet_len,
1344                                          pattern, packet_len);
1345   return 0;
1346 }
1347
1348 static void
1349 free_sym_cache (struct sym_cache *sym)
1350 {
1351   if (sym != NULL)
1352     {
1353       free (sym->name);
1354       free (sym);
1355     }
1356 }
1357
1358 void
1359 clear_symbol_cache (struct sym_cache **symcache_p)
1360 {
1361   struct sym_cache *sym, *next;
1362
1363   /* Check the cache first.  */
1364   for (sym = *symcache_p; sym; sym = next)
1365     {
1366       next = sym->next;
1367       free_sym_cache (sym);
1368     }
1369
1370   *symcache_p = NULL;
1371 }
1372
1373 /* Get the address of NAME, and return it in ADDRP if found.  if
1374    MAY_ASK_GDB is false, assume symbol cache misses are failures.
1375    Returns 1 if the symbol is found, 0 if it is not, -1 on error.  */
1376
1377 int
1378 look_up_one_symbol (const char *name, CORE_ADDR *addrp, int may_ask_gdb)
1379 {
1380   char own_buf[266], *p, *q;
1381   int len;
1382   struct sym_cache *sym;
1383   struct process_info *proc;
1384
1385   proc = current_process ();
1386
1387   /* Check the cache first.  */
1388   for (sym = proc->symbol_cache; sym; sym = sym->next)
1389     if (strcmp (name, sym->name) == 0)
1390       {
1391         *addrp = sym->addr;
1392         return 1;
1393       }
1394
1395   /* It might not be an appropriate time to look up a symbol,
1396      e.g. while we're trying to fetch registers.  */
1397   if (!may_ask_gdb)
1398     return 0;
1399
1400   /* Send the request.  */
1401   strcpy (own_buf, "qSymbol:");
1402   bin2hex ((const gdb_byte *) name, own_buf + strlen ("qSymbol:"),
1403           strlen (name));
1404   if (putpkt (own_buf) < 0)
1405     return -1;
1406
1407   /* FIXME:  Eventually add buffer overflow checking (to getpkt?)  */
1408   len = getpkt (own_buf);
1409   if (len < 0)
1410     return -1;
1411
1412   /* We ought to handle pretty much any packet at this point while we
1413      wait for the qSymbol "response".  That requires re-entering the
1414      main loop.  For now, this is an adequate approximation; allow
1415      GDB to read from memory while it figures out the address of the
1416      symbol.  */
1417   while (own_buf[0] == 'm')
1418     {
1419       CORE_ADDR mem_addr;
1420       unsigned char *mem_buf;
1421       unsigned int mem_len;
1422
1423       decode_m_packet (&own_buf[1], &mem_addr, &mem_len);
1424       mem_buf = xmalloc (mem_len);
1425       if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
1426         convert_int_to_ascii (mem_buf, own_buf, mem_len);
1427       else
1428         write_enn (own_buf);
1429       free (mem_buf);
1430       if (putpkt (own_buf) < 0)
1431         return -1;
1432       len = getpkt (own_buf);
1433       if (len < 0)
1434         return -1;
1435     }
1436
1437   if (strncmp (own_buf, "qSymbol:", strlen ("qSymbol:")) != 0)
1438     {
1439       warning ("Malformed response to qSymbol, ignoring: %s\n", own_buf);
1440       return -1;
1441     }
1442
1443   p = own_buf + strlen ("qSymbol:");
1444   q = p;
1445   while (*q && *q != ':')
1446     q++;
1447
1448   /* Make sure we found a value for the symbol.  */
1449   if (p == q || *q == '\0')
1450     return 0;
1451
1452   decode_address (addrp, p, q - p);
1453
1454   /* Save the symbol in our cache.  */
1455   sym = xmalloc (sizeof (*sym));
1456   sym->name = xstrdup (name);
1457   sym->addr = *addrp;
1458   sym->next = proc->symbol_cache;
1459   proc->symbol_cache = sym;
1460
1461   return 1;
1462 }
1463
1464 /* Relocate an instruction to execute at a different address.  OLDLOC
1465    is the address in the inferior memory where the instruction to
1466    relocate is currently at.  On input, TO points to the destination
1467    where we want the instruction to be copied (and possibly adjusted)
1468    to.  On output, it points to one past the end of the resulting
1469    instruction(s).  The effect of executing the instruction at TO
1470    shall be the same as if executing it at OLDLOC.  For example, call
1471    instructions that implicitly push the return address on the stack
1472    should be adjusted to return to the instruction after OLDLOC;
1473    relative branches, and other PC-relative instructions need the
1474    offset adjusted; etc.  Returns 0 on success, -1 on failure.  */
1475
1476 int
1477 relocate_instruction (CORE_ADDR *to, CORE_ADDR oldloc)
1478 {
1479   char own_buf[266];
1480   int len;
1481   ULONGEST written = 0;
1482
1483   /* Send the request.  */
1484   strcpy (own_buf, "qRelocInsn:");
1485   sprintf (own_buf, "qRelocInsn:%s;%s", paddress (oldloc),
1486            paddress (*to));
1487   if (putpkt (own_buf) < 0)
1488     return -1;
1489
1490   /* FIXME:  Eventually add buffer overflow checking (to getpkt?)  */
1491   len = getpkt (own_buf);
1492   if (len < 0)
1493     return -1;
1494
1495   /* We ought to handle pretty much any packet at this point while we
1496      wait for the qRelocInsn "response".  That requires re-entering
1497      the main loop.  For now, this is an adequate approximation; allow
1498      GDB to access memory.  */
1499   while (own_buf[0] == 'm' || own_buf[0] == 'M' || own_buf[0] == 'X')
1500     {
1501       CORE_ADDR mem_addr;
1502       unsigned char *mem_buf = NULL;
1503       unsigned int mem_len;
1504
1505       if (own_buf[0] == 'm')
1506         {
1507           decode_m_packet (&own_buf[1], &mem_addr, &mem_len);
1508           mem_buf = xmalloc (mem_len);
1509           if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
1510             convert_int_to_ascii (mem_buf, own_buf, mem_len);
1511           else
1512             write_enn (own_buf);
1513         }
1514       else if (own_buf[0] == 'X')
1515         {
1516           if (decode_X_packet (&own_buf[1], len - 1, &mem_addr,
1517                                &mem_len, &mem_buf) < 0
1518               || write_inferior_memory (mem_addr, mem_buf, mem_len) != 0)
1519             write_enn (own_buf);
1520           else
1521             write_ok (own_buf);
1522         }
1523       else
1524         {
1525           decode_M_packet (&own_buf[1], &mem_addr, &mem_len, &mem_buf);
1526           if (write_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
1527             write_ok (own_buf);
1528           else
1529             write_enn (own_buf);
1530         }
1531       free (mem_buf);
1532       if (putpkt (own_buf) < 0)
1533         return -1;
1534       len = getpkt (own_buf);
1535       if (len < 0)
1536         return -1;
1537     }
1538
1539   if (own_buf[0] == 'E')
1540     {
1541       warning ("An error occurred while relocating an instruction: %s\n",
1542                own_buf);
1543       return -1;
1544     }
1545
1546   if (strncmp (own_buf, "qRelocInsn:", strlen ("qRelocInsn:")) != 0)
1547     {
1548       warning ("Malformed response to qRelocInsn, ignoring: %s\n",
1549                own_buf);
1550       return -1;
1551     }
1552
1553   unpack_varlen_hex (own_buf + strlen ("qRelocInsn:"), &written);
1554
1555   *to += written;
1556   return 0;
1557 }
1558
1559 void
1560 monitor_output (const char *msg)
1561 {
1562   int len = strlen (msg);
1563   char *buf = xmalloc (len * 2 + 2);
1564
1565   buf[0] = 'O';
1566   bin2hex ((const gdb_byte *) msg, buf + 1, len);
1567
1568   putpkt (buf);
1569   free (buf);
1570 }
1571
1572 #endif