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