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