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