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