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