Introduce common/symbol.h
[deliverable/binutils-gdb.git] / gdb / gdbserver / remote-utils.c
1 /* Remote utility routines for the remote server for GDB.
2 Copyright (C) 1986-2014 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 #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 #include <unistd.h>
55 #if HAVE_ARPA_INET_H
56 #include <arpa/inet.h>
57 #endif
58 #include <sys/stat.h>
59
60 #if USE_WIN32API
61 #include <winsock2.h>
62 #endif
63
64 #if __QNX__
65 #include <sys/iomgr.h>
66 #endif /* __QNX__ */
67
68 #ifndef HAVE_SOCKLEN_T
69 typedef int socklen_t;
70 #endif
71
72 #ifndef IN_PROCESS_AGENT
73
74 #if USE_WIN32API
75 # define INVALID_DESCRIPTOR INVALID_SOCKET
76 #else
77 # define INVALID_DESCRIPTOR -1
78 #endif
79
80 /* Extra value for readchar_callback. */
81 enum {
82 /* The callback is currently not scheduled. */
83 NOT_SCHEDULED = -1
84 };
85
86 /* Status of the readchar callback.
87 Either NOT_SCHEDULED or the callback id. */
88 static int readchar_callback = NOT_SCHEDULED;
89
90 static int readchar (void);
91 static void reset_readchar (void);
92 static void reschedule (void);
93
94 /* A cache entry for a successfully looked-up symbol. */
95 struct sym_cache
96 {
97 char *name;
98 CORE_ADDR addr;
99 struct sym_cache *next;
100 };
101
102 int remote_debug = 0;
103 struct ui_file *gdb_stdlog;
104
105 static int remote_is_stdio = 0;
106
107 static gdb_fildes_t remote_desc = INVALID_DESCRIPTOR;
108 static gdb_fildes_t listen_desc = INVALID_DESCRIPTOR;
109
110 /* FIXME headerize? */
111 extern int using_threads;
112 extern int debug_threads;
113
114 /* If true, then GDB has requested noack mode. */
115 int noack_mode = 0;
116 /* If true, then we tell GDB to use noack mode by default. */
117 int transport_is_reliable = 0;
118
119 #ifdef USE_WIN32API
120 # define read(fd, buf, len) recv (fd, (char *) buf, len, 0)
121 # define write(fd, buf, len) send (fd, (char *) buf, len, 0)
122 #endif
123
124 int
125 gdb_connected (void)
126 {
127 return remote_desc != INVALID_DESCRIPTOR;
128 }
129
130 /* Return true if the remote connection is over stdio. */
131
132 int
133 remote_connection_is_stdio (void)
134 {
135 return remote_is_stdio;
136 }
137
138 static void
139 enable_async_notification (int fd)
140 {
141 #if defined(F_SETFL) && defined (FASYNC)
142 int save_fcntl_flags;
143
144 save_fcntl_flags = fcntl (fd, F_GETFL, 0);
145 fcntl (fd, F_SETFL, save_fcntl_flags | FASYNC);
146 #if defined (F_SETOWN)
147 fcntl (fd, F_SETOWN, getpid ());
148 #endif
149 #endif
150 }
151
152 static int
153 handle_accept_event (int err, gdb_client_data client_data)
154 {
155 struct sockaddr_in sockaddr;
156 socklen_t tmp;
157
158 if (debug_threads)
159 debug_printf ("handling possible accept event\n");
160
161 tmp = sizeof (sockaddr);
162 remote_desc = accept (listen_desc, (struct sockaddr *) &sockaddr, &tmp);
163 if (remote_desc == -1)
164 perror_with_name ("Accept failed");
165
166 /* Enable TCP keep alive process. */
167 tmp = 1;
168 setsockopt (remote_desc, SOL_SOCKET, SO_KEEPALIVE,
169 (char *) &tmp, sizeof (tmp));
170
171 /* Tell TCP not to delay small packets. This greatly speeds up
172 interactive response. */
173 tmp = 1;
174 setsockopt (remote_desc, IPPROTO_TCP, TCP_NODELAY,
175 (char *) &tmp, sizeof (tmp));
176
177 #ifndef USE_WIN32API
178 signal (SIGPIPE, SIG_IGN); /* If we don't do this, then gdbserver simply
179 exits when the remote side dies. */
180 #endif
181
182 if (run_once)
183 {
184 #ifndef USE_WIN32API
185 close (listen_desc); /* No longer need this */
186 #else
187 closesocket (listen_desc); /* No longer need this */
188 #endif
189 }
190
191 /* Even if !RUN_ONCE no longer notice new connections. Still keep the
192 descriptor open for add_file_handler to wait for a new connection. */
193 delete_file_handler (listen_desc);
194
195 /* Convert IP address to string. */
196 fprintf (stderr, "Remote debugging from host %s\n",
197 inet_ntoa (sockaddr.sin_addr));
198
199 enable_async_notification (remote_desc);
200
201 /* Register the event loop handler. */
202 add_file_handler (remote_desc, handle_serial_event, NULL);
203
204 /* We have a new GDB connection now. If we were disconnected
205 tracing, there's a window where the target could report a stop
206 event to the event loop, and since we have a connection now, we'd
207 try to send vStopped notifications to GDB. But, don't do that
208 until GDB as selected all-stop/non-stop, and has queried the
209 threads' status ('?'). */
210 target_async (0);
211
212 return 0;
213 }
214
215 /* Prepare for a later connection to a remote debugger.
216 NAME is the filename used for communication. */
217
218 void
219 remote_prepare (char *name)
220 {
221 char *port_str;
222 #ifdef USE_WIN32API
223 static int winsock_initialized;
224 #endif
225 int port;
226 struct sockaddr_in sockaddr;
227 socklen_t tmp;
228 char *port_end;
229
230 remote_is_stdio = 0;
231 if (strcmp (name, STDIO_CONNECTION_NAME) == 0)
232 {
233 /* We need to record fact that we're using stdio sooner than the
234 call to remote_open so start_inferior knows the connection is
235 via stdio. */
236 remote_is_stdio = 1;
237 transport_is_reliable = 1;
238 return;
239 }
240
241 port_str = strchr (name, ':');
242 if (port_str == NULL)
243 {
244 transport_is_reliable = 0;
245 return;
246 }
247
248 port = strtoul (port_str + 1, &port_end, 10);
249 if (port_str[1] == '\0' || *port_end != '\0')
250 error ("Bad port argument: %s", name);
251
252 #ifdef USE_WIN32API
253 if (!winsock_initialized)
254 {
255 WSADATA wsad;
256
257 WSAStartup (MAKEWORD (1, 0), &wsad);
258 winsock_initialized = 1;
259 }
260 #endif
261
262 listen_desc = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
263 if (listen_desc == -1)
264 perror_with_name ("Can't open socket");
265
266 /* Allow rapid reuse of this port. */
267 tmp = 1;
268 setsockopt (listen_desc, SOL_SOCKET, SO_REUSEADDR, (char *) &tmp,
269 sizeof (tmp));
270
271 sockaddr.sin_family = PF_INET;
272 sockaddr.sin_port = htons (port);
273 sockaddr.sin_addr.s_addr = INADDR_ANY;
274
275 if (bind (listen_desc, (struct sockaddr *) &sockaddr, sizeof (sockaddr))
276 || listen (listen_desc, 1))
277 perror_with_name ("Can't bind address");
278
279 transport_is_reliable = 1;
280 }
281
282 /* Open a connection to a remote debugger.
283 NAME is the filename used for communication. */
284
285 void
286 remote_open (char *name)
287 {
288 char *port_str;
289
290 port_str = strchr (name, ':');
291 #ifdef USE_WIN32API
292 if (port_str == NULL)
293 error ("Only <host>:<port> is supported on this platform.");
294 #endif
295
296 if (strcmp (name, STDIO_CONNECTION_NAME) == 0)
297 {
298 fprintf (stderr, "Remote debugging using stdio\n");
299
300 /* Use stdin as the handle of the connection.
301 We only select on reads, for example. */
302 remote_desc = fileno (stdin);
303
304 enable_async_notification (remote_desc);
305
306 /* Register the event loop handler. */
307 add_file_handler (remote_desc, handle_serial_event, NULL);
308 }
309 #ifndef USE_WIN32API
310 else if (port_str == NULL)
311 {
312 struct stat statbuf;
313
314 if (stat (name, &statbuf) == 0
315 && (S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode)))
316 remote_desc = open (name, O_RDWR);
317 else
318 {
319 errno = EINVAL;
320 remote_desc = -1;
321 }
322
323 if (remote_desc < 0)
324 perror_with_name ("Could not open remote device");
325
326 #ifdef HAVE_TERMIOS
327 {
328 struct termios termios;
329 tcgetattr (remote_desc, &termios);
330
331 termios.c_iflag = 0;
332 termios.c_oflag = 0;
333 termios.c_lflag = 0;
334 termios.c_cflag &= ~(CSIZE | PARENB);
335 termios.c_cflag |= CLOCAL | CS8;
336 termios.c_cc[VMIN] = 1;
337 termios.c_cc[VTIME] = 0;
338
339 tcsetattr (remote_desc, TCSANOW, &termios);
340 }
341 #endif
342
343 #ifdef HAVE_TERMIO
344 {
345 struct termio termio;
346 ioctl (remote_desc, TCGETA, &termio);
347
348 termio.c_iflag = 0;
349 termio.c_oflag = 0;
350 termio.c_lflag = 0;
351 termio.c_cflag &= ~(CSIZE | PARENB);
352 termio.c_cflag |= CLOCAL | CS8;
353 termio.c_cc[VMIN] = 1;
354 termio.c_cc[VTIME] = 0;
355
356 ioctl (remote_desc, TCSETA, &termio);
357 }
358 #endif
359
360 #ifdef HAVE_SGTTY
361 {
362 struct sgttyb sg;
363
364 ioctl (remote_desc, TIOCGETP, &sg);
365 sg.sg_flags = RAW;
366 ioctl (remote_desc, TIOCSETP, &sg);
367 }
368 #endif
369
370 fprintf (stderr, "Remote debugging using %s\n", name);
371
372 enable_async_notification (remote_desc);
373
374 /* Register the event loop handler. */
375 add_file_handler (remote_desc, handle_serial_event, NULL);
376 }
377 #endif /* USE_WIN32API */
378 else
379 {
380 int port;
381 socklen_t len;
382 struct sockaddr_in sockaddr;
383
384 len = sizeof (sockaddr);
385 if (getsockname (listen_desc,
386 (struct sockaddr *) &sockaddr, &len) < 0
387 || len < sizeof (sockaddr))
388 perror_with_name ("Can't determine port");
389 port = ntohs (sockaddr.sin_port);
390
391 fprintf (stderr, "Listening on port %d\n", port);
392 fflush (stderr);
393
394 /* Register the event loop handler. */
395 add_file_handler (listen_desc, handle_accept_event, NULL);
396 }
397 }
398
399 void
400 remote_close (void)
401 {
402 delete_file_handler (remote_desc);
403
404 #ifdef USE_WIN32API
405 closesocket (remote_desc);
406 #else
407 if (! remote_connection_is_stdio ())
408 close (remote_desc);
409 #endif
410 remote_desc = INVALID_DESCRIPTOR;
411
412 reset_readchar ();
413 }
414
415 #endif
416
417 #ifndef IN_PROCESS_AGENT
418
419 void
420 decode_address (CORE_ADDR *addrp, const char *start, int len)
421 {
422 CORE_ADDR addr;
423 char ch;
424 int i;
425
426 addr = 0;
427 for (i = 0; i < len; i++)
428 {
429 ch = start[i];
430 addr = addr << 4;
431 addr = addr | (fromhex (ch) & 0x0f);
432 }
433 *addrp = addr;
434 }
435
436 const char *
437 decode_address_to_semicolon (CORE_ADDR *addrp, const char *start)
438 {
439 const char *end;
440
441 end = start;
442 while (*end != '\0' && *end != ';')
443 end++;
444
445 decode_address (addrp, start, end - start);
446
447 if (*end == ';')
448 end++;
449 return end;
450 }
451
452 #endif
453
454 #ifndef IN_PROCESS_AGENT
455
456 /* Look for a sequence of characters which can be run-length encoded.
457 If there are any, update *CSUM and *P. Otherwise, output the
458 single character. Return the number of characters consumed. */
459
460 static int
461 try_rle (char *buf, int remaining, unsigned char *csum, char **p)
462 {
463 int n;
464
465 /* Always output the character. */
466 *csum += buf[0];
467 *(*p)++ = buf[0];
468
469 /* Don't go past '~'. */
470 if (remaining > 97)
471 remaining = 97;
472
473 for (n = 1; n < remaining; n++)
474 if (buf[n] != buf[0])
475 break;
476
477 /* N is the index of the first character not the same as buf[0].
478 buf[0] is counted twice, so by decrementing N, we get the number
479 of characters the RLE sequence will replace. */
480 n--;
481
482 if (n < 3)
483 return 1;
484
485 /* Skip the frame characters. The manual says to skip '+' and '-'
486 also, but there's no reason to. Unfortunately these two unusable
487 characters double the encoded length of a four byte zero
488 value. */
489 while (n + 29 == '$' || n + 29 == '#')
490 n--;
491
492 *csum += '*';
493 *(*p)++ = '*';
494 *csum += n + 29;
495 *(*p)++ = n + 29;
496
497 return n + 1;
498 }
499
500 #endif
501
502 #ifndef IN_PROCESS_AGENT
503
504 /* Write a PTID to BUF. Returns BUF+CHARACTERS_WRITTEN. */
505
506 char *
507 write_ptid (char *buf, ptid_t ptid)
508 {
509 int pid, tid;
510
511 if (multi_process)
512 {
513 pid = ptid_get_pid (ptid);
514 if (pid < 0)
515 buf += sprintf (buf, "p-%x.", -pid);
516 else
517 buf += sprintf (buf, "p%x.", pid);
518 }
519 tid = ptid_get_lwp (ptid);
520 if (tid < 0)
521 buf += sprintf (buf, "-%x", -tid);
522 else
523 buf += sprintf (buf, "%x", tid);
524
525 return buf;
526 }
527
528 ULONGEST
529 hex_or_minus_one (char *buf, char **obuf)
530 {
531 ULONGEST ret;
532
533 if (strncmp (buf, "-1", 2) == 0)
534 {
535 ret = (ULONGEST) -1;
536 buf += 2;
537 }
538 else
539 buf = unpack_varlen_hex (buf, &ret);
540
541 if (obuf)
542 *obuf = buf;
543
544 return ret;
545 }
546
547 /* Extract a PTID from BUF. If non-null, OBUF is set to the to one
548 passed the last parsed char. Returns null_ptid on error. */
549 ptid_t
550 read_ptid (char *buf, char **obuf)
551 {
552 char *p = buf;
553 char *pp;
554 ULONGEST pid = 0, tid = 0;
555
556 if (*p == 'p')
557 {
558 /* Multi-process ptid. */
559 pp = unpack_varlen_hex (p + 1, &pid);
560 if (*pp != '.')
561 error ("invalid remote ptid: %s\n", p);
562
563 p = pp + 1;
564
565 tid = hex_or_minus_one (p, &pp);
566
567 if (obuf)
568 *obuf = pp;
569 return ptid_build (pid, tid, 0);
570 }
571
572 /* No multi-process. Just a tid. */
573 tid = hex_or_minus_one (p, &pp);
574
575 /* Since the stub is not sending a process id, then default to
576 what's in the current inferior. */
577 pid = ptid_get_pid (current_ptid);
578
579 if (obuf)
580 *obuf = pp;
581 return ptid_build (pid, tid, 0);
582 }
583
584 /* Write COUNT bytes in BUF to the client.
585 The result is the number of bytes written or -1 if error.
586 This may return less than COUNT. */
587
588 static int
589 write_prim (const void *buf, int count)
590 {
591 if (remote_connection_is_stdio ())
592 return write (fileno (stdout), buf, count);
593 else
594 return write (remote_desc, buf, count);
595 }
596
597 /* Read COUNT bytes from the client and store in BUF.
598 The result is the number of bytes read or -1 if error.
599 This may return less than COUNT. */
600
601 static int
602 read_prim (void *buf, int count)
603 {
604 if (remote_connection_is_stdio ())
605 return read (fileno (stdin), buf, count);
606 else
607 return read (remote_desc, buf, count);
608 }
609
610 /* Send a packet to the remote machine, with error checking.
611 The data of the packet is in BUF, and the length of the
612 packet is in CNT. Returns >= 0 on success, -1 otherwise. */
613
614 static int
615 putpkt_binary_1 (char *buf, int cnt, int is_notif)
616 {
617 int i;
618 unsigned char csum = 0;
619 char *buf2;
620 char *p;
621 int cc;
622
623 buf2 = xmalloc (strlen ("$") + cnt + strlen ("#nn") + 1);
624
625 /* Copy the packet into buffer BUF2, encapsulating it
626 and giving it a checksum. */
627
628 p = buf2;
629 if (is_notif)
630 *p++ = '%';
631 else
632 *p++ = '$';
633
634 for (i = 0; i < cnt;)
635 i += try_rle (buf + i, cnt - i, &csum, &p);
636
637 *p++ = '#';
638 *p++ = tohex ((csum >> 4) & 0xf);
639 *p++ = tohex (csum & 0xf);
640
641 *p = '\0';
642
643 /* Send it over and over until we get a positive ack. */
644
645 do
646 {
647 if (write_prim (buf2, p - buf2) != p - buf2)
648 {
649 perror ("putpkt(write)");
650 free (buf2);
651 return -1;
652 }
653
654 if (noack_mode || is_notif)
655 {
656 /* Don't expect an ack then. */
657 if (remote_debug)
658 {
659 if (is_notif)
660 fprintf (stderr, "putpkt (\"%s\"); [notif]\n", buf2);
661 else
662 fprintf (stderr, "putpkt (\"%s\"); [noack mode]\n", buf2);
663 fflush (stderr);
664 }
665 break;
666 }
667
668 if (remote_debug)
669 {
670 fprintf (stderr, "putpkt (\"%s\"); [looking for ack]\n", buf2);
671 fflush (stderr);
672 }
673
674 cc = readchar ();
675
676 if (cc < 0)
677 {
678 free (buf2);
679 return -1;
680 }
681
682 if (remote_debug)
683 {
684 fprintf (stderr, "[received '%c' (0x%x)]\n", cc, cc);
685 fflush (stderr);
686 }
687
688 /* Check for an input interrupt while we're here. */
689 if (cc == '\003' && current_inferior != NULL)
690 (*the_target->request_interrupt) ();
691 }
692 while (cc != '+');
693
694 free (buf2);
695 return 1; /* Success! */
696 }
697
698 int
699 putpkt_binary (char *buf, int cnt)
700 {
701 return putpkt_binary_1 (buf, cnt, 0);
702 }
703
704 /* Send a packet to the remote machine, with error checking. The data
705 of the packet is in BUF, and the packet should be a NUL-terminated
706 string. Returns >= 0 on success, -1 otherwise. */
707
708 int
709 putpkt (char *buf)
710 {
711 return putpkt_binary (buf, strlen (buf));
712 }
713
714 int
715 putpkt_notif (char *buf)
716 {
717 return putpkt_binary_1 (buf, strlen (buf), 1);
718 }
719
720 /* Come here when we get an input interrupt from the remote side. This
721 interrupt should only be active while we are waiting for the child to do
722 something. Thus this assumes readchar:bufcnt is 0.
723 About the only thing that should come through is a ^C, which
724 will cause us to request child interruption. */
725
726 static void
727 input_interrupt (int unused)
728 {
729 fd_set readset;
730 struct timeval immediate = { 0, 0 };
731
732 /* Protect against spurious interrupts. This has been observed to
733 be a problem under NetBSD 1.4 and 1.5. */
734
735 FD_ZERO (&readset);
736 FD_SET (remote_desc, &readset);
737 if (select (remote_desc + 1, &readset, 0, 0, &immediate) > 0)
738 {
739 int cc;
740 char c = 0;
741
742 cc = read_prim (&c, 1);
743
744 if (cc != 1 || c != '\003' || current_inferior == NULL)
745 {
746 fprintf (stderr, "input_interrupt, count = %d c = %d ('%c')\n",
747 cc, c, c);
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_inferior;
1110 const char **regp;
1111 struct regcache *regcache;
1112
1113 sprintf (buf, "T%02x", status->value.sig);
1114 buf += strlen (buf);
1115
1116 saved_inferior = current_inferior;
1117
1118 current_inferior = find_thread_ptid (ptid);
1119
1120 regp = current_target_desc ()->expedite_regs;
1121
1122 regcache = get_thread_regcache (current_inferior, 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
1144 while (*regp)
1145 {
1146 buf = outreg (regcache, find_regno (regcache->tdesc, *regp), buf);
1147 regp ++;
1148 }
1149 *buf = '\0';
1150
1151 /* Formerly, if the debugger had not used any thread features
1152 we would not burden it with a thread status response. This
1153 was for the benefit of GDB 4.13 and older. However, in
1154 recent GDB versions the check (``if (cont_thread != 0)'')
1155 does not have the desired effect because of sillyness in
1156 the way that the remote protocol handles specifying a
1157 thread. Since thread support relies on qSymbol support
1158 anyway, assume GDB can handle threads. */
1159
1160 if (using_threads && !disable_packet_Tthread)
1161 {
1162 /* This if (1) ought to be unnecessary. But remote_wait
1163 in GDB will claim this event belongs to inferior_ptid
1164 if we do not specify a thread, and there's no way for
1165 gdbserver to know what inferior_ptid is. */
1166 if (1 || !ptid_equal (general_thread, ptid))
1167 {
1168 int core = -1;
1169 /* In non-stop, don't change the general thread behind
1170 GDB's back. */
1171 if (!non_stop)
1172 general_thread = ptid;
1173 sprintf (buf, "thread:");
1174 buf += strlen (buf);
1175 buf = write_ptid (buf, ptid);
1176 strcat (buf, ";");
1177 buf += strlen (buf);
1178
1179 core = target_core_of_thread (ptid);
1180
1181 if (core != -1)
1182 {
1183 sprintf (buf, "core:");
1184 buf += strlen (buf);
1185 sprintf (buf, "%x", core);
1186 strcat (buf, ";");
1187 buf += strlen (buf);
1188 }
1189 }
1190 }
1191
1192 if (dlls_changed)
1193 {
1194 strcpy (buf, "library:;");
1195 buf += strlen (buf);
1196 dlls_changed = 0;
1197 }
1198
1199 current_inferior = saved_inferior;
1200 }
1201 break;
1202 case TARGET_WAITKIND_EXITED:
1203 if (multi_process)
1204 sprintf (buf, "W%x;process:%x",
1205 status->value.integer, ptid_get_pid (ptid));
1206 else
1207 sprintf (buf, "W%02x", status->value.integer);
1208 break;
1209 case TARGET_WAITKIND_SIGNALLED:
1210 if (multi_process)
1211 sprintf (buf, "X%x;process:%x",
1212 status->value.sig, ptid_get_pid (ptid));
1213 else
1214 sprintf (buf, "X%02x", status->value.sig);
1215 break;
1216 default:
1217 error ("unhandled waitkind");
1218 break;
1219 }
1220 }
1221
1222 void
1223 decode_m_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr)
1224 {
1225 int i = 0, j = 0;
1226 char ch;
1227 *mem_addr_ptr = *len_ptr = 0;
1228
1229 while ((ch = from[i++]) != ',')
1230 {
1231 *mem_addr_ptr = *mem_addr_ptr << 4;
1232 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1233 }
1234
1235 for (j = 0; j < 4; j++)
1236 {
1237 if ((ch = from[i++]) == 0)
1238 break;
1239 *len_ptr = *len_ptr << 4;
1240 *len_ptr |= fromhex (ch) & 0x0f;
1241 }
1242 }
1243
1244 void
1245 decode_M_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr,
1246 unsigned char **to_p)
1247 {
1248 int i = 0;
1249 char ch;
1250 *mem_addr_ptr = *len_ptr = 0;
1251
1252 while ((ch = from[i++]) != ',')
1253 {
1254 *mem_addr_ptr = *mem_addr_ptr << 4;
1255 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1256 }
1257
1258 while ((ch = from[i++]) != ':')
1259 {
1260 *len_ptr = *len_ptr << 4;
1261 *len_ptr |= fromhex (ch) & 0x0f;
1262 }
1263
1264 if (*to_p == NULL)
1265 *to_p = xmalloc (*len_ptr);
1266
1267 hex2bin (&from[i++], *to_p, *len_ptr);
1268 }
1269
1270 int
1271 decode_X_packet (char *from, int packet_len, CORE_ADDR *mem_addr_ptr,
1272 unsigned int *len_ptr, unsigned char **to_p)
1273 {
1274 int i = 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 while ((ch = from[i++]) != ':')
1285 {
1286 *len_ptr = *len_ptr << 4;
1287 *len_ptr |= fromhex (ch) & 0x0f;
1288 }
1289
1290 if (*to_p == NULL)
1291 *to_p = xmalloc (*len_ptr);
1292
1293 if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len - i,
1294 *to_p, *len_ptr) != *len_ptr)
1295 return -1;
1296
1297 return 0;
1298 }
1299
1300 /* Decode a qXfer write request. */
1301
1302 int
1303 decode_xfer_write (char *buf, int packet_len, CORE_ADDR *offset,
1304 unsigned int *len, unsigned char *data)
1305 {
1306 char ch;
1307 char *b = buf;
1308
1309 /* Extract the offset. */
1310 *offset = 0;
1311 while ((ch = *buf++) != ':')
1312 {
1313 *offset = *offset << 4;
1314 *offset |= fromhex (ch) & 0x0f;
1315 }
1316
1317 /* Get encoded data. */
1318 packet_len -= buf - b;
1319 *len = remote_unescape_input ((const gdb_byte *) buf, packet_len,
1320 data, packet_len);
1321 return 0;
1322 }
1323
1324 /* Decode the parameters of a qSearch:memory packet. */
1325
1326 int
1327 decode_search_memory_packet (const char *buf, int packet_len,
1328 CORE_ADDR *start_addrp,
1329 CORE_ADDR *search_space_lenp,
1330 gdb_byte *pattern, unsigned int *pattern_lenp)
1331 {
1332 const char *p = buf;
1333
1334 p = decode_address_to_semicolon (start_addrp, p);
1335 p = decode_address_to_semicolon (search_space_lenp, p);
1336 packet_len -= p - buf;
1337 *pattern_lenp = remote_unescape_input ((const gdb_byte *) p, packet_len,
1338 pattern, packet_len);
1339 return 0;
1340 }
1341
1342 static void
1343 free_sym_cache (struct sym_cache *sym)
1344 {
1345 if (sym != NULL)
1346 {
1347 free (sym->name);
1348 free (sym);
1349 }
1350 }
1351
1352 void
1353 clear_symbol_cache (struct sym_cache **symcache_p)
1354 {
1355 struct sym_cache *sym, *next;
1356
1357 /* Check the cache first. */
1358 for (sym = *symcache_p; sym; sym = next)
1359 {
1360 next = sym->next;
1361 free_sym_cache (sym);
1362 }
1363
1364 *symcache_p = NULL;
1365 }
1366
1367 /* Get the address of NAME, and return it in ADDRP if found. if
1368 MAY_ASK_GDB is false, assume symbol cache misses are failures.
1369 Returns 1 if the symbol is found, 0 if it is not, -1 on error. */
1370
1371 int
1372 look_up_one_symbol (const char *name, CORE_ADDR *addrp, int may_ask_gdb)
1373 {
1374 char own_buf[266], *p, *q;
1375 int len;
1376 struct sym_cache *sym;
1377 struct process_info *proc;
1378
1379 proc = current_process ();
1380
1381 /* Check the cache first. */
1382 for (sym = proc->symbol_cache; sym; sym = sym->next)
1383 if (strcmp (name, sym->name) == 0)
1384 {
1385 *addrp = sym->addr;
1386 return 1;
1387 }
1388
1389 /* It might not be an appropriate time to look up a symbol,
1390 e.g. while we're trying to fetch registers. */
1391 if (!may_ask_gdb)
1392 return 0;
1393
1394 /* Send the request. */
1395 strcpy (own_buf, "qSymbol:");
1396 bin2hex ((const gdb_byte *) name, own_buf + strlen ("qSymbol:"),
1397 strlen (name));
1398 if (putpkt (own_buf) < 0)
1399 return -1;
1400
1401 /* FIXME: Eventually add buffer overflow checking (to getpkt?) */
1402 len = getpkt (own_buf);
1403 if (len < 0)
1404 return -1;
1405
1406 /* We ought to handle pretty much any packet at this point while we
1407 wait for the qSymbol "response". That requires re-entering the
1408 main loop. For now, this is an adequate approximation; allow
1409 GDB to read from memory while it figures out the address of the
1410 symbol. */
1411 while (own_buf[0] == 'm')
1412 {
1413 CORE_ADDR mem_addr;
1414 unsigned char *mem_buf;
1415 unsigned int mem_len;
1416
1417 decode_m_packet (&own_buf[1], &mem_addr, &mem_len);
1418 mem_buf = xmalloc (mem_len);
1419 if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
1420 bin2hex (mem_buf, own_buf, mem_len);
1421 else
1422 write_enn (own_buf);
1423 free (mem_buf);
1424 if (putpkt (own_buf) < 0)
1425 return -1;
1426 len = getpkt (own_buf);
1427 if (len < 0)
1428 return -1;
1429 }
1430
1431 if (strncmp (own_buf, "qSymbol:", strlen ("qSymbol:")) != 0)
1432 {
1433 warning ("Malformed response to qSymbol, ignoring: %s\n", own_buf);
1434 return -1;
1435 }
1436
1437 p = own_buf + strlen ("qSymbol:");
1438 q = p;
1439 while (*q && *q != ':')
1440 q++;
1441
1442 /* Make sure we found a value for the symbol. */
1443 if (p == q || *q == '\0')
1444 return 0;
1445
1446 decode_address (addrp, p, q - p);
1447
1448 /* Save the symbol in our cache. */
1449 sym = xmalloc (sizeof (*sym));
1450 sym->name = xstrdup (name);
1451 sym->addr = *addrp;
1452 sym->next = proc->symbol_cache;
1453 proc->symbol_cache = sym;
1454
1455 return 1;
1456 }
1457
1458 /* Relocate an instruction to execute at a different address. OLDLOC
1459 is the address in the inferior memory where the instruction to
1460 relocate is currently at. On input, TO points to the destination
1461 where we want the instruction to be copied (and possibly adjusted)
1462 to. On output, it points to one past the end of the resulting
1463 instruction(s). The effect of executing the instruction at TO
1464 shall be the same as if executing it at OLDLOC. For example, call
1465 instructions that implicitly push the return address on the stack
1466 should be adjusted to return to the instruction after OLDLOC;
1467 relative branches, and other PC-relative instructions need the
1468 offset adjusted; etc. Returns 0 on success, -1 on failure. */
1469
1470 int
1471 relocate_instruction (CORE_ADDR *to, CORE_ADDR oldloc)
1472 {
1473 char own_buf[266];
1474 int len;
1475 ULONGEST written = 0;
1476
1477 /* Send the request. */
1478 strcpy (own_buf, "qRelocInsn:");
1479 sprintf (own_buf, "qRelocInsn:%s;%s", paddress (oldloc),
1480 paddress (*to));
1481 if (putpkt (own_buf) < 0)
1482 return -1;
1483
1484 /* FIXME: Eventually add buffer overflow checking (to getpkt?) */
1485 len = getpkt (own_buf);
1486 if (len < 0)
1487 return -1;
1488
1489 /* We ought to handle pretty much any packet at this point while we
1490 wait for the qRelocInsn "response". That requires re-entering
1491 the main loop. For now, this is an adequate approximation; allow
1492 GDB to access memory. */
1493 while (own_buf[0] == 'm' || own_buf[0] == 'M' || own_buf[0] == 'X')
1494 {
1495 CORE_ADDR mem_addr;
1496 unsigned char *mem_buf = NULL;
1497 unsigned int mem_len;
1498
1499 if (own_buf[0] == 'm')
1500 {
1501 decode_m_packet (&own_buf[1], &mem_addr, &mem_len);
1502 mem_buf = xmalloc (mem_len);
1503 if (read_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
1504 bin2hex (mem_buf, own_buf, mem_len);
1505 else
1506 write_enn (own_buf);
1507 }
1508 else if (own_buf[0] == 'X')
1509 {
1510 if (decode_X_packet (&own_buf[1], len - 1, &mem_addr,
1511 &mem_len, &mem_buf) < 0
1512 || write_inferior_memory (mem_addr, mem_buf, mem_len) != 0)
1513 write_enn (own_buf);
1514 else
1515 write_ok (own_buf);
1516 }
1517 else
1518 {
1519 decode_M_packet (&own_buf[1], &mem_addr, &mem_len, &mem_buf);
1520 if (write_inferior_memory (mem_addr, mem_buf, mem_len) == 0)
1521 write_ok (own_buf);
1522 else
1523 write_enn (own_buf);
1524 }
1525 free (mem_buf);
1526 if (putpkt (own_buf) < 0)
1527 return -1;
1528 len = getpkt (own_buf);
1529 if (len < 0)
1530 return -1;
1531 }
1532
1533 if (own_buf[0] == 'E')
1534 {
1535 warning ("An error occurred while relocating an instruction: %s\n",
1536 own_buf);
1537 return -1;
1538 }
1539
1540 if (strncmp (own_buf, "qRelocInsn:", strlen ("qRelocInsn:")) != 0)
1541 {
1542 warning ("Malformed response to qRelocInsn, ignoring: %s\n",
1543 own_buf);
1544 return -1;
1545 }
1546
1547 unpack_varlen_hex (own_buf + strlen ("qRelocInsn:"), &written);
1548
1549 *to += written;
1550 return 0;
1551 }
1552
1553 void
1554 monitor_output (const char *msg)
1555 {
1556 int len = strlen (msg);
1557 char *buf = xmalloc (len * 2 + 2);
1558
1559 buf[0] = 'O';
1560 bin2hex ((const gdb_byte *) msg, buf + 1, len);
1561
1562 putpkt (buf);
1563 free (buf);
1564 }
1565
1566 #endif
This page took 0.062833 seconds and 4 git commands to generate.