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