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