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