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