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