]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/gdbserver/server.c
Extended-remote follow-exec
[thirdparty/binutils-gdb.git] / gdb / gdbserver / server.c
1 /* Main code for remote server for GDB.
2 Copyright (C) 1989-2015 Free Software Foundation, Inc.
3
4 This file is part of GDB.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18
19 #include "server.h"
20 #include "gdbthread.h"
21 #include "agent.h"
22 #include "notif.h"
23 #include "tdesc.h"
24 #include "rsp-low.h"
25
26 #include <ctype.h>
27 #include <unistd.h>
28 #if HAVE_SIGNAL_H
29 #include <signal.h>
30 #endif
31 #include "gdb_vecs.h"
32 #include "gdb_wait.h"
33 #include "btrace-common.h"
34 #include "filestuff.h"
35 #include "tracepoint.h"
36 #include "dll.h"
37 #include "hostio.h"
38
39 /* The thread set with an `Hc' packet. `Hc' is deprecated in favor of
40 `vCont'. Note the multi-process extensions made `vCont' a
41 requirement, so `Hc pPID.TID' is pretty much undefined. So
42 CONT_THREAD can be null_ptid for no `Hc' thread, minus_one_ptid for
43 resuming all threads of the process (again, `Hc' isn't used for
44 multi-process), or a specific thread ptid_t. */
45 ptid_t cont_thread;
46
47 /* The thread set with an `Hg' packet. */
48 ptid_t general_thread;
49
50 int server_waiting;
51
52 int extended_protocol;
53 static int response_needed;
54 static int exit_requested;
55
56 /* --once: Exit after the first connection has closed. */
57 int run_once;
58
59 int multi_process;
60 int report_fork_events;
61 int report_vfork_events;
62 int report_exec_events;
63 int non_stop;
64 int swbreak_feature;
65 int hwbreak_feature;
66
67 /* Whether we should attempt to disable the operating system's address
68 space randomization feature before starting an inferior. */
69 int disable_randomization = 1;
70
71 static char **program_argv, **wrapper_argv;
72
73 int pass_signals[GDB_SIGNAL_LAST];
74 int program_signals[GDB_SIGNAL_LAST];
75 int program_signals_p;
76
77 /* The PID of the originally created or attached inferior. Used to
78 send signals to the process when GDB sends us an asynchronous interrupt
79 (user hitting Control-C in the client), and to wait for the child to exit
80 when no longer debugging it. */
81
82 unsigned long signal_pid;
83
84 #ifdef SIGTTOU
85 /* A file descriptor for the controlling terminal. */
86 int terminal_fd;
87
88 /* TERMINAL_FD's original foreground group. */
89 pid_t old_foreground_pgrp;
90
91 /* Hand back terminal ownership to the original foreground group. */
92
93 static void
94 restore_old_foreground_pgrp (void)
95 {
96 tcsetpgrp (terminal_fd, old_foreground_pgrp);
97 }
98 #endif
99
100 /* Set if you want to disable optional thread related packets support
101 in gdbserver, for the sake of testing GDB against stubs that don't
102 support them. */
103 int disable_packet_vCont;
104 int disable_packet_Tthread;
105 int disable_packet_qC;
106 int disable_packet_qfThreadInfo;
107
108 /* Last status reported to GDB. */
109 static struct target_waitstatus last_status;
110 static ptid_t last_ptid;
111
112 static char *own_buf;
113 static unsigned char *mem_buf;
114
115 /* A sub-class of 'struct notif_event' for stop, holding information
116 relative to a single stop reply. We keep a queue of these to
117 push to GDB in non-stop mode. */
118
119 struct vstop_notif
120 {
121 struct notif_event base;
122
123 /* Thread or process that got the event. */
124 ptid_t ptid;
125
126 /* Event info. */
127 struct target_waitstatus status;
128 };
129
130 /* The current btrace configuration. This is gdbserver's mirror of GDB's
131 btrace configuration. */
132 static struct btrace_config current_btrace_conf;
133
134 DEFINE_QUEUE_P (notif_event_p);
135
136 /* Put a stop reply to the stop reply queue. */
137
138 static void
139 queue_stop_reply (ptid_t ptid, struct target_waitstatus *status)
140 {
141 struct vstop_notif *new_notif = XNEW (struct vstop_notif);
142
143 new_notif->ptid = ptid;
144 new_notif->status = *status;
145
146 notif_event_enque (&notif_stop, (struct notif_event *) new_notif);
147 }
148
149 static int
150 remove_all_on_match_ptid (QUEUE (notif_event_p) *q,
151 QUEUE_ITER (notif_event_p) *iter,
152 struct notif_event *event,
153 void *data)
154 {
155 ptid_t filter_ptid = *(ptid_t *) data;
156 struct vstop_notif *vstop_event = (struct vstop_notif *) event;
157
158 if (ptid_match (vstop_event->ptid, filter_ptid))
159 {
160 if (q->free_func != NULL)
161 q->free_func (event);
162
163 QUEUE_remove_elem (notif_event_p, q, iter);
164 }
165
166 return 1;
167 }
168
169 /* See server.h. */
170
171 void
172 discard_queued_stop_replies (ptid_t ptid)
173 {
174 QUEUE_iterate (notif_event_p, notif_stop.queue,
175 remove_all_on_match_ptid, &ptid);
176 }
177
178 static void
179 vstop_notif_reply (struct notif_event *event, char *own_buf)
180 {
181 struct vstop_notif *vstop = (struct vstop_notif *) event;
182
183 prepare_resume_reply (own_buf, vstop->ptid, &vstop->status);
184 }
185
186 struct notif_server notif_stop =
187 {
188 "vStopped", "Stop", NULL, vstop_notif_reply,
189 };
190
191 static int
192 target_running (void)
193 {
194 return get_first_thread () != NULL;
195 }
196
197 static int
198 start_inferior (char **argv)
199 {
200 char **new_argv = argv;
201
202 if (wrapper_argv != NULL)
203 {
204 int i, count = 1;
205
206 for (i = 0; wrapper_argv[i] != NULL; i++)
207 count++;
208 for (i = 0; argv[i] != NULL; i++)
209 count++;
210 new_argv = XALLOCAVEC (char *, count);
211 count = 0;
212 for (i = 0; wrapper_argv[i] != NULL; i++)
213 new_argv[count++] = wrapper_argv[i];
214 for (i = 0; argv[i] != NULL; i++)
215 new_argv[count++] = argv[i];
216 new_argv[count] = NULL;
217 }
218
219 if (debug_threads)
220 {
221 int i;
222 for (i = 0; new_argv[i]; ++i)
223 debug_printf ("new_argv[%d] = \"%s\"\n", i, new_argv[i]);
224 debug_flush ();
225 }
226
227 #ifdef SIGTTOU
228 signal (SIGTTOU, SIG_DFL);
229 signal (SIGTTIN, SIG_DFL);
230 #endif
231
232 signal_pid = create_inferior (new_argv[0], new_argv);
233
234 /* FIXME: we don't actually know at this point that the create
235 actually succeeded. We won't know that until we wait. */
236 fprintf (stderr, "Process %s created; pid = %ld\n", argv[0],
237 signal_pid);
238 fflush (stderr);
239
240 #ifdef SIGTTOU
241 signal (SIGTTOU, SIG_IGN);
242 signal (SIGTTIN, SIG_IGN);
243 terminal_fd = fileno (stderr);
244 old_foreground_pgrp = tcgetpgrp (terminal_fd);
245 tcsetpgrp (terminal_fd, signal_pid);
246 atexit (restore_old_foreground_pgrp);
247 #endif
248
249 if (wrapper_argv != NULL)
250 {
251 struct thread_resume resume_info;
252
253 memset (&resume_info, 0, sizeof (resume_info));
254 resume_info.thread = pid_to_ptid (signal_pid);
255 resume_info.kind = resume_continue;
256 resume_info.sig = 0;
257
258 last_ptid = mywait (pid_to_ptid (signal_pid), &last_status, 0, 0);
259
260 if (last_status.kind == TARGET_WAITKIND_STOPPED)
261 {
262 do
263 {
264 (*the_target->resume) (&resume_info, 1);
265
266 last_ptid = mywait (pid_to_ptid (signal_pid), &last_status, 0, 0);
267 if (last_status.kind != TARGET_WAITKIND_STOPPED)
268 break;
269
270 current_thread->last_resume_kind = resume_stop;
271 current_thread->last_status = last_status;
272 }
273 while (last_status.value.sig != GDB_SIGNAL_TRAP);
274 }
275 target_arch_setup ();
276 return signal_pid;
277 }
278
279 /* Wait till we are at 1st instruction in program, return new pid
280 (assuming success). */
281 last_ptid = mywait (pid_to_ptid (signal_pid), &last_status, 0, 0);
282
283 target_arch_setup ();
284
285 if (last_status.kind != TARGET_WAITKIND_EXITED
286 && last_status.kind != TARGET_WAITKIND_SIGNALLED)
287 {
288 current_thread->last_resume_kind = resume_stop;
289 current_thread->last_status = last_status;
290 }
291 else
292 mourn_inferior (find_process_pid (ptid_get_pid (last_ptid)));
293
294 return signal_pid;
295 }
296
297 static int
298 attach_inferior (int pid)
299 {
300 /* myattach should return -1 if attaching is unsupported,
301 0 if it succeeded, and call error() otherwise. */
302
303 if (myattach (pid) != 0)
304 return -1;
305
306 fprintf (stderr, "Attached; pid = %d\n", pid);
307 fflush (stderr);
308
309 /* FIXME - It may be that we should get the SIGNAL_PID from the
310 attach function, so that it can be the main thread instead of
311 whichever we were told to attach to. */
312 signal_pid = pid;
313
314 if (!non_stop)
315 {
316 last_ptid = mywait (pid_to_ptid (pid), &last_status, 0, 0);
317
318 /* GDB knows to ignore the first SIGSTOP after attaching to a running
319 process using the "attach" command, but this is different; it's
320 just using "target remote". Pretend it's just starting up. */
321 if (last_status.kind == TARGET_WAITKIND_STOPPED
322 && last_status.value.sig == GDB_SIGNAL_STOP)
323 last_status.value.sig = GDB_SIGNAL_TRAP;
324
325 current_thread->last_resume_kind = resume_stop;
326 current_thread->last_status = last_status;
327 }
328
329 return 0;
330 }
331
332 extern int remote_debug;
333
334 /* Decode a qXfer read request. Return 0 if everything looks OK,
335 or -1 otherwise. */
336
337 static int
338 decode_xfer_read (char *buf, CORE_ADDR *ofs, unsigned int *len)
339 {
340 /* After the read marker and annex, qXfer looks like a
341 traditional 'm' packet. */
342 decode_m_packet (buf, ofs, len);
343
344 return 0;
345 }
346
347 static int
348 decode_xfer (char *buf, char **object, char **rw, char **annex, char **offset)
349 {
350 /* Extract and NUL-terminate the object. */
351 *object = buf;
352 while (*buf && *buf != ':')
353 buf++;
354 if (*buf == '\0')
355 return -1;
356 *buf++ = 0;
357
358 /* Extract and NUL-terminate the read/write action. */
359 *rw = buf;
360 while (*buf && *buf != ':')
361 buf++;
362 if (*buf == '\0')
363 return -1;
364 *buf++ = 0;
365
366 /* Extract and NUL-terminate the annex. */
367 *annex = buf;
368 while (*buf && *buf != ':')
369 buf++;
370 if (*buf == '\0')
371 return -1;
372 *buf++ = 0;
373
374 *offset = buf;
375 return 0;
376 }
377
378 /* Write the response to a successful qXfer read. Returns the
379 length of the (binary) data stored in BUF, corresponding
380 to as much of DATA/LEN as we could fit. IS_MORE controls
381 the first character of the response. */
382 static int
383 write_qxfer_response (char *buf, const void *data, int len, int is_more)
384 {
385 int out_len;
386
387 if (is_more)
388 buf[0] = 'm';
389 else
390 buf[0] = 'l';
391
392 return remote_escape_output (data, len, 1, (unsigned char *) buf + 1,
393 &out_len, PBUFSIZ - 2) + 1;
394 }
395
396 /* Handle btrace enabling in BTS format. */
397
398 static const char *
399 handle_btrace_enable_bts (struct thread_info *thread)
400 {
401 if (thread->btrace != NULL)
402 return "E.Btrace already enabled.";
403
404 current_btrace_conf.format = BTRACE_FORMAT_BTS;
405 thread->btrace = target_enable_btrace (thread->entry.id,
406 &current_btrace_conf);
407 if (thread->btrace == NULL)
408 return "E.Could not enable btrace.";
409
410 return NULL;
411 }
412
413 /* Handle btrace enabling in Intel(R) Processor Trace format. */
414
415 static const char *
416 handle_btrace_enable_pt (struct thread_info *thread)
417 {
418 if (thread->btrace != NULL)
419 return "E.Btrace already enabled.";
420
421 current_btrace_conf.format = BTRACE_FORMAT_PT;
422 thread->btrace = target_enable_btrace (thread->entry.id,
423 &current_btrace_conf);
424 if (thread->btrace == NULL)
425 return "E.Could not enable btrace.";
426
427 return NULL;
428 }
429
430 /* Handle btrace disabling. */
431
432 static const char *
433 handle_btrace_disable (struct thread_info *thread)
434 {
435
436 if (thread->btrace == NULL)
437 return "E.Branch tracing not enabled.";
438
439 if (target_disable_btrace (thread->btrace) != 0)
440 return "E.Could not disable branch tracing.";
441
442 thread->btrace = NULL;
443 return NULL;
444 }
445
446 /* Handle the "Qbtrace" packet. */
447
448 static int
449 handle_btrace_general_set (char *own_buf)
450 {
451 struct thread_info *thread;
452 const char *err;
453 char *op;
454
455 if (!startswith (own_buf, "Qbtrace:"))
456 return 0;
457
458 op = own_buf + strlen ("Qbtrace:");
459
460 if (ptid_equal (general_thread, null_ptid)
461 || ptid_equal (general_thread, minus_one_ptid))
462 {
463 strcpy (own_buf, "E.Must select a single thread.");
464 return -1;
465 }
466
467 thread = find_thread_ptid (general_thread);
468 if (thread == NULL)
469 {
470 strcpy (own_buf, "E.No such thread.");
471 return -1;
472 }
473
474 err = NULL;
475
476 if (strcmp (op, "bts") == 0)
477 err = handle_btrace_enable_bts (thread);
478 else if (strcmp (op, "pt") == 0)
479 err = handle_btrace_enable_pt (thread);
480 else if (strcmp (op, "off") == 0)
481 err = handle_btrace_disable (thread);
482 else
483 err = "E.Bad Qbtrace operation. Use bts, pt, or off.";
484
485 if (err != 0)
486 strcpy (own_buf, err);
487 else
488 write_ok (own_buf);
489
490 return 1;
491 }
492
493 /* Handle the "Qbtrace-conf" packet. */
494
495 static int
496 handle_btrace_conf_general_set (char *own_buf)
497 {
498 struct thread_info *thread;
499 char *op;
500
501 if (!startswith (own_buf, "Qbtrace-conf:"))
502 return 0;
503
504 op = own_buf + strlen ("Qbtrace-conf:");
505
506 if (ptid_equal (general_thread, null_ptid)
507 || ptid_equal (general_thread, minus_one_ptid))
508 {
509 strcpy (own_buf, "E.Must select a single thread.");
510 return -1;
511 }
512
513 thread = find_thread_ptid (general_thread);
514 if (thread == NULL)
515 {
516 strcpy (own_buf, "E.No such thread.");
517 return -1;
518 }
519
520 if (startswith (op, "bts:size="))
521 {
522 unsigned long size;
523 char *endp = NULL;
524
525 errno = 0;
526 size = strtoul (op + strlen ("bts:size="), &endp, 16);
527 if (endp == NULL || *endp != 0 || errno != 0 || size > UINT_MAX)
528 {
529 strcpy (own_buf, "E.Bad size value.");
530 return -1;
531 }
532
533 current_btrace_conf.bts.size = (unsigned int) size;
534 }
535 else if (strncmp (op, "pt:size=", strlen ("pt:size=")) == 0)
536 {
537 unsigned long size;
538 char *endp = NULL;
539
540 errno = 0;
541 size = strtoul (op + strlen ("pt:size="), &endp, 16);
542 if (endp == NULL || *endp != 0 || errno != 0 || size > UINT_MAX)
543 {
544 strcpy (own_buf, "E.Bad size value.");
545 return -1;
546 }
547
548 current_btrace_conf.pt.size = (unsigned int) size;
549 }
550 else
551 {
552 strcpy (own_buf, "E.Bad Qbtrace configuration option.");
553 return -1;
554 }
555
556 write_ok (own_buf);
557 return 1;
558 }
559
560 /* Handle all of the extended 'Q' packets. */
561
562 static void
563 handle_general_set (char *own_buf)
564 {
565 if (startswith (own_buf, "QPassSignals:"))
566 {
567 int numsigs = (int) GDB_SIGNAL_LAST, i;
568 const char *p = own_buf + strlen ("QPassSignals:");
569 CORE_ADDR cursig;
570
571 p = decode_address_to_semicolon (&cursig, p);
572 for (i = 0; i < numsigs; i++)
573 {
574 if (i == cursig)
575 {
576 pass_signals[i] = 1;
577 if (*p == '\0')
578 /* Keep looping, to clear the remaining signals. */
579 cursig = -1;
580 else
581 p = decode_address_to_semicolon (&cursig, p);
582 }
583 else
584 pass_signals[i] = 0;
585 }
586 strcpy (own_buf, "OK");
587 return;
588 }
589
590 if (startswith (own_buf, "QProgramSignals:"))
591 {
592 int numsigs = (int) GDB_SIGNAL_LAST, i;
593 const char *p = own_buf + strlen ("QProgramSignals:");
594 CORE_ADDR cursig;
595
596 program_signals_p = 1;
597
598 p = decode_address_to_semicolon (&cursig, p);
599 for (i = 0; i < numsigs; i++)
600 {
601 if (i == cursig)
602 {
603 program_signals[i] = 1;
604 if (*p == '\0')
605 /* Keep looping, to clear the remaining signals. */
606 cursig = -1;
607 else
608 p = decode_address_to_semicolon (&cursig, p);
609 }
610 else
611 program_signals[i] = 0;
612 }
613 strcpy (own_buf, "OK");
614 return;
615 }
616
617 if (strcmp (own_buf, "QStartNoAckMode") == 0)
618 {
619 if (remote_debug)
620 {
621 fprintf (stderr, "[noack mode enabled]\n");
622 fflush (stderr);
623 }
624
625 noack_mode = 1;
626 write_ok (own_buf);
627 return;
628 }
629
630 if (startswith (own_buf, "QNonStop:"))
631 {
632 char *mode = own_buf + 9;
633 int req = -1;
634 const char *req_str;
635
636 if (strcmp (mode, "0") == 0)
637 req = 0;
638 else if (strcmp (mode, "1") == 0)
639 req = 1;
640 else
641 {
642 /* We don't know what this mode is, so complain to
643 GDB. */
644 fprintf (stderr, "Unknown non-stop mode requested: %s\n",
645 own_buf);
646 write_enn (own_buf);
647 return;
648 }
649
650 req_str = req ? "non-stop" : "all-stop";
651 if (start_non_stop (req) != 0)
652 {
653 fprintf (stderr, "Setting %s mode failed\n", req_str);
654 write_enn (own_buf);
655 return;
656 }
657
658 non_stop = req;
659
660 if (remote_debug)
661 fprintf (stderr, "[%s mode enabled]\n", req_str);
662
663 write_ok (own_buf);
664 return;
665 }
666
667 if (startswith (own_buf, "QDisableRandomization:"))
668 {
669 char *packet = own_buf + strlen ("QDisableRandomization:");
670 ULONGEST setting;
671
672 unpack_varlen_hex (packet, &setting);
673 disable_randomization = setting;
674
675 if (remote_debug)
676 {
677 if (disable_randomization)
678 fprintf (stderr, "[address space randomization disabled]\n");
679 else
680 fprintf (stderr, "[address space randomization enabled]\n");
681 }
682
683 write_ok (own_buf);
684 return;
685 }
686
687 if (target_supports_tracepoints ()
688 && handle_tracepoint_general_set (own_buf))
689 return;
690
691 if (startswith (own_buf, "QAgent:"))
692 {
693 char *mode = own_buf + strlen ("QAgent:");
694 int req = 0;
695
696 if (strcmp (mode, "0") == 0)
697 req = 0;
698 else if (strcmp (mode, "1") == 0)
699 req = 1;
700 else
701 {
702 /* We don't know what this value is, so complain to GDB. */
703 sprintf (own_buf, "E.Unknown QAgent value");
704 return;
705 }
706
707 /* Update the flag. */
708 use_agent = req;
709 if (remote_debug)
710 fprintf (stderr, "[%s agent]\n", req ? "Enable" : "Disable");
711 write_ok (own_buf);
712 return;
713 }
714
715 if (handle_btrace_general_set (own_buf))
716 return;
717
718 if (handle_btrace_conf_general_set (own_buf))
719 return;
720
721 /* Otherwise we didn't know what packet it was. Say we didn't
722 understand it. */
723 own_buf[0] = 0;
724 }
725
726 static const char *
727 get_features_xml (const char *annex)
728 {
729 const struct target_desc *desc = current_target_desc ();
730
731 /* `desc->xmltarget' defines what to return when looking for the
732 "target.xml" file. Its contents can either be verbatim XML code
733 (prefixed with a '@') or else the name of the actual XML file to
734 be used in place of "target.xml".
735
736 This variable is set up from the auto-generated
737 init_registers_... routine for the current target. */
738
739 if (desc->xmltarget != NULL && strcmp (annex, "target.xml") == 0)
740 {
741 if (*desc->xmltarget == '@')
742 return desc->xmltarget + 1;
743 else
744 annex = desc->xmltarget;
745 }
746
747 #ifdef USE_XML
748 {
749 extern const char *const xml_builtin[][2];
750 int i;
751
752 /* Look for the annex. */
753 for (i = 0; xml_builtin[i][0] != NULL; i++)
754 if (strcmp (annex, xml_builtin[i][0]) == 0)
755 break;
756
757 if (xml_builtin[i][0] != NULL)
758 return xml_builtin[i][1];
759 }
760 #endif
761
762 return NULL;
763 }
764
765 void
766 monitor_show_help (void)
767 {
768 monitor_output ("The following monitor commands are supported:\n");
769 monitor_output (" set debug <0|1>\n");
770 monitor_output (" Enable general debugging messages\n");
771 monitor_output (" set debug-hw-points <0|1>\n");
772 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
773 monitor_output (" set remote-debug <0|1>\n");
774 monitor_output (" Enable remote protocol debugging messages\n");
775 monitor_output (" set debug-format option1[,option2,...]\n");
776 monitor_output (" Add additional information to debugging messages\n");
777 monitor_output (" Options: all, none");
778 monitor_output (", timestamp");
779 monitor_output ("\n");
780 monitor_output (" exit\n");
781 monitor_output (" Quit GDBserver\n");
782 }
783
784 /* Read trace frame or inferior memory. Returns the number of bytes
785 actually read, zero when no further transfer is possible, and -1 on
786 error. Return of a positive value smaller than LEN does not
787 indicate there's no more to be read, only the end of the transfer.
788 E.g., when GDB reads memory from a traceframe, a first request may
789 be served from a memory block that does not cover the whole request
790 length. A following request gets the rest served from either
791 another block (of the same traceframe) or from the read-only
792 regions. */
793
794 static int
795 gdb_read_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
796 {
797 int res;
798
799 if (current_traceframe >= 0)
800 {
801 ULONGEST nbytes;
802 ULONGEST length = len;
803
804 if (traceframe_read_mem (current_traceframe,
805 memaddr, myaddr, len, &nbytes))
806 return -1;
807 /* Data read from trace buffer, we're done. */
808 if (nbytes > 0)
809 return nbytes;
810 if (!in_readonly_region (memaddr, length))
811 return -1;
812 /* Otherwise we have a valid readonly case, fall through. */
813 /* (assume no half-trace half-real blocks for now) */
814 }
815
816 res = prepare_to_access_memory ();
817 if (res == 0)
818 {
819 if (set_desired_thread (1))
820 res = read_inferior_memory (memaddr, myaddr, len);
821 else
822 res = 1;
823 done_accessing_memory ();
824
825 return res == 0 ? len : -1;
826 }
827 else
828 return -1;
829 }
830
831 /* Write trace frame or inferior memory. Actually, writing to trace
832 frames is forbidden. */
833
834 static int
835 gdb_write_memory (CORE_ADDR memaddr, const unsigned char *myaddr, int len)
836 {
837 if (current_traceframe >= 0)
838 return EIO;
839 else
840 {
841 int ret;
842
843 ret = prepare_to_access_memory ();
844 if (ret == 0)
845 {
846 if (set_desired_thread (1))
847 ret = write_inferior_memory (memaddr, myaddr, len);
848 else
849 ret = EIO;
850 done_accessing_memory ();
851 }
852 return ret;
853 }
854 }
855
856 /* Subroutine of handle_search_memory to simplify it. */
857
858 static int
859 handle_search_memory_1 (CORE_ADDR start_addr, CORE_ADDR search_space_len,
860 gdb_byte *pattern, unsigned pattern_len,
861 gdb_byte *search_buf,
862 unsigned chunk_size, unsigned search_buf_size,
863 CORE_ADDR *found_addrp)
864 {
865 /* Prime the search buffer. */
866
867 if (gdb_read_memory (start_addr, search_buf, search_buf_size)
868 != search_buf_size)
869 {
870 warning ("Unable to access %ld bytes of target "
871 "memory at 0x%lx, halting search.",
872 (long) search_buf_size, (long) start_addr);
873 return -1;
874 }
875
876 /* Perform the search.
877
878 The loop is kept simple by allocating [N + pattern-length - 1] bytes.
879 When we've scanned N bytes we copy the trailing bytes to the start and
880 read in another N bytes. */
881
882 while (search_space_len >= pattern_len)
883 {
884 gdb_byte *found_ptr;
885 unsigned nr_search_bytes = (search_space_len < search_buf_size
886 ? search_space_len
887 : search_buf_size);
888
889 found_ptr = memmem (search_buf, nr_search_bytes, pattern, pattern_len);
890
891 if (found_ptr != NULL)
892 {
893 CORE_ADDR found_addr = start_addr + (found_ptr - search_buf);
894 *found_addrp = found_addr;
895 return 1;
896 }
897
898 /* Not found in this chunk, skip to next chunk. */
899
900 /* Don't let search_space_len wrap here, it's unsigned. */
901 if (search_space_len >= chunk_size)
902 search_space_len -= chunk_size;
903 else
904 search_space_len = 0;
905
906 if (search_space_len >= pattern_len)
907 {
908 unsigned keep_len = search_buf_size - chunk_size;
909 CORE_ADDR read_addr = start_addr + chunk_size + keep_len;
910 int nr_to_read;
911
912 /* Copy the trailing part of the previous iteration to the front
913 of the buffer for the next iteration. */
914 memcpy (search_buf, search_buf + chunk_size, keep_len);
915
916 nr_to_read = (search_space_len - keep_len < chunk_size
917 ? search_space_len - keep_len
918 : chunk_size);
919
920 if (gdb_read_memory (read_addr, search_buf + keep_len,
921 nr_to_read) != search_buf_size)
922 {
923 warning ("Unable to access %ld bytes of target memory "
924 "at 0x%lx, halting search.",
925 (long) nr_to_read, (long) read_addr);
926 return -1;
927 }
928
929 start_addr += chunk_size;
930 }
931 }
932
933 /* Not found. */
934
935 return 0;
936 }
937
938 /* Handle qSearch:memory packets. */
939
940 static void
941 handle_search_memory (char *own_buf, int packet_len)
942 {
943 CORE_ADDR start_addr;
944 CORE_ADDR search_space_len;
945 gdb_byte *pattern;
946 unsigned int pattern_len;
947 /* NOTE: also defined in find.c testcase. */
948 #define SEARCH_CHUNK_SIZE 16000
949 const unsigned chunk_size = SEARCH_CHUNK_SIZE;
950 /* Buffer to hold memory contents for searching. */
951 gdb_byte *search_buf;
952 unsigned search_buf_size;
953 int found;
954 CORE_ADDR found_addr;
955 int cmd_name_len = sizeof ("qSearch:memory:") - 1;
956
957 pattern = malloc (packet_len);
958 if (pattern == NULL)
959 {
960 error ("Unable to allocate memory to perform the search");
961 strcpy (own_buf, "E00");
962 return;
963 }
964 if (decode_search_memory_packet (own_buf + cmd_name_len,
965 packet_len - cmd_name_len,
966 &start_addr, &search_space_len,
967 pattern, &pattern_len) < 0)
968 {
969 free (pattern);
970 error ("Error in parsing qSearch:memory packet");
971 strcpy (own_buf, "E00");
972 return;
973 }
974
975 search_buf_size = chunk_size + pattern_len - 1;
976
977 /* No point in trying to allocate a buffer larger than the search space. */
978 if (search_space_len < search_buf_size)
979 search_buf_size = search_space_len;
980
981 search_buf = malloc (search_buf_size);
982 if (search_buf == NULL)
983 {
984 free (pattern);
985 error ("Unable to allocate memory to perform the search");
986 strcpy (own_buf, "E00");
987 return;
988 }
989
990 found = handle_search_memory_1 (start_addr, search_space_len,
991 pattern, pattern_len,
992 search_buf, chunk_size, search_buf_size,
993 &found_addr);
994
995 if (found > 0)
996 sprintf (own_buf, "1,%lx", (long) found_addr);
997 else if (found == 0)
998 strcpy (own_buf, "0");
999 else
1000 strcpy (own_buf, "E00");
1001
1002 free (search_buf);
1003 free (pattern);
1004 }
1005
1006 #define require_running(BUF) \
1007 if (!target_running ()) \
1008 { \
1009 write_enn (BUF); \
1010 return; \
1011 }
1012
1013 /* Parse options to --debug-format= and "monitor set debug-format".
1014 ARG is the text after "--debug-format=" or "monitor set debug-format".
1015 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1016 This triggers calls to monitor_output.
1017 The result is NULL if all options were parsed ok, otherwise an error
1018 message which the caller must free.
1019
1020 N.B. These commands affect all debug format settings, they are not
1021 cumulative. If a format is not specified, it is turned off.
1022 However, we don't go to extra trouble with things like
1023 "monitor set debug-format all,none,timestamp".
1024 Instead we just parse them one at a time, in order.
1025
1026 The syntax for "monitor set debug" we support here is not identical
1027 to gdb's "set debug foo on|off" because we also use this function to
1028 parse "--debug-format=foo,bar". */
1029
1030 static char *
1031 parse_debug_format_options (const char *arg, int is_monitor)
1032 {
1033 VEC (char_ptr) *options;
1034 int ix;
1035 char *option;
1036
1037 /* First turn all debug format options off. */
1038 debug_timestamp = 0;
1039
1040 /* First remove leading spaces, for "monitor set debug-format". */
1041 while (isspace (*arg))
1042 ++arg;
1043
1044 options = delim_string_to_char_ptr_vec (arg, ',');
1045
1046 for (ix = 0; VEC_iterate (char_ptr, options, ix, option); ++ix)
1047 {
1048 if (strcmp (option, "all") == 0)
1049 {
1050 debug_timestamp = 1;
1051 if (is_monitor)
1052 monitor_output ("All extra debug format options enabled.\n");
1053 }
1054 else if (strcmp (option, "none") == 0)
1055 {
1056 debug_timestamp = 0;
1057 if (is_monitor)
1058 monitor_output ("All extra debug format options disabled.\n");
1059 }
1060 else if (strcmp (option, "timestamp") == 0)
1061 {
1062 debug_timestamp = 1;
1063 if (is_monitor)
1064 monitor_output ("Timestamps will be added to debug output.\n");
1065 }
1066 else if (*option == '\0')
1067 {
1068 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1069 continue;
1070 }
1071 else
1072 {
1073 char *msg = xstrprintf ("Unknown debug-format argument: \"%s\"\n",
1074 option);
1075
1076 free_char_ptr_vec (options);
1077 return msg;
1078 }
1079 }
1080
1081 free_char_ptr_vec (options);
1082 return NULL;
1083 }
1084
1085 /* Handle monitor commands not handled by target-specific handlers. */
1086
1087 static void
1088 handle_monitor_command (char *mon, char *own_buf)
1089 {
1090 if (strcmp (mon, "set debug 1") == 0)
1091 {
1092 debug_threads = 1;
1093 monitor_output ("Debug output enabled.\n");
1094 }
1095 else if (strcmp (mon, "set debug 0") == 0)
1096 {
1097 debug_threads = 0;
1098 monitor_output ("Debug output disabled.\n");
1099 }
1100 else if (strcmp (mon, "set debug-hw-points 1") == 0)
1101 {
1102 show_debug_regs = 1;
1103 monitor_output ("H/W point debugging output enabled.\n");
1104 }
1105 else if (strcmp (mon, "set debug-hw-points 0") == 0)
1106 {
1107 show_debug_regs = 0;
1108 monitor_output ("H/W point debugging output disabled.\n");
1109 }
1110 else if (strcmp (mon, "set remote-debug 1") == 0)
1111 {
1112 remote_debug = 1;
1113 monitor_output ("Protocol debug output enabled.\n");
1114 }
1115 else if (strcmp (mon, "set remote-debug 0") == 0)
1116 {
1117 remote_debug = 0;
1118 monitor_output ("Protocol debug output disabled.\n");
1119 }
1120 else if (startswith (mon, "set debug-format "))
1121 {
1122 char *error_msg
1123 = parse_debug_format_options (mon + sizeof ("set debug-format ") - 1,
1124 1);
1125
1126 if (error_msg != NULL)
1127 {
1128 monitor_output (error_msg);
1129 monitor_show_help ();
1130 write_enn (own_buf);
1131 xfree (error_msg);
1132 }
1133 }
1134 else if (strcmp (mon, "help") == 0)
1135 monitor_show_help ();
1136 else if (strcmp (mon, "exit") == 0)
1137 exit_requested = 1;
1138 else
1139 {
1140 monitor_output ("Unknown monitor command.\n\n");
1141 monitor_show_help ();
1142 write_enn (own_buf);
1143 }
1144 }
1145
1146 /* Associates a callback with each supported qXfer'able object. */
1147
1148 struct qxfer
1149 {
1150 /* The object this handler handles. */
1151 const char *object;
1152
1153 /* Request that the target transfer up to LEN 8-bit bytes of the
1154 target's OBJECT. The OFFSET, for a seekable object, specifies
1155 the starting point. The ANNEX can be used to provide additional
1156 data-specific information to the target.
1157
1158 Return the number of bytes actually transfered, zero when no
1159 further transfer is possible, -1 on error, -2 when the transfer
1160 is not supported, and -3 on a verbose error message that should
1161 be preserved. Return of a positive value smaller than LEN does
1162 not indicate the end of the object, only the end of the transfer.
1163
1164 One, and only one, of readbuf or writebuf must be non-NULL. */
1165 int (*xfer) (const char *annex,
1166 gdb_byte *readbuf, const gdb_byte *writebuf,
1167 ULONGEST offset, LONGEST len);
1168 };
1169
1170 /* Handle qXfer:auxv:read. */
1171
1172 static int
1173 handle_qxfer_auxv (const char *annex,
1174 gdb_byte *readbuf, const gdb_byte *writebuf,
1175 ULONGEST offset, LONGEST len)
1176 {
1177 if (the_target->read_auxv == NULL || writebuf != NULL)
1178 return -2;
1179
1180 if (annex[0] != '\0' || current_thread == NULL)
1181 return -1;
1182
1183 return (*the_target->read_auxv) (offset, readbuf, len);
1184 }
1185
1186 /* Handle qXfer:exec-file:read. */
1187
1188 static int
1189 handle_qxfer_exec_file (const char *const_annex,
1190 gdb_byte *readbuf, const gdb_byte *writebuf,
1191 ULONGEST offset, LONGEST len)
1192 {
1193 char *file;
1194 ULONGEST pid;
1195 int total_len;
1196
1197 if (the_target->pid_to_exec_file == NULL || writebuf != NULL)
1198 return -2;
1199
1200 if (const_annex[0] == '\0')
1201 {
1202 if (current_thread == NULL)
1203 return -1;
1204
1205 pid = pid_of (current_thread);
1206 }
1207 else
1208 {
1209 char *annex = alloca (strlen (const_annex) + 1);
1210
1211 strcpy (annex, const_annex);
1212 annex = unpack_varlen_hex (annex, &pid);
1213
1214 if (annex[0] != '\0')
1215 return -1;
1216 }
1217
1218 if (pid <= 0)
1219 return -1;
1220
1221 file = (*the_target->pid_to_exec_file) (pid);
1222 if (file == NULL)
1223 return -1;
1224
1225 total_len = strlen (file);
1226
1227 if (offset > total_len)
1228 return -1;
1229
1230 if (offset + len > total_len)
1231 len = total_len - offset;
1232
1233 memcpy (readbuf, file + offset, len);
1234 return len;
1235 }
1236
1237 /* Handle qXfer:features:read. */
1238
1239 static int
1240 handle_qxfer_features (const char *annex,
1241 gdb_byte *readbuf, const gdb_byte *writebuf,
1242 ULONGEST offset, LONGEST len)
1243 {
1244 const char *document;
1245 size_t total_len;
1246
1247 if (writebuf != NULL)
1248 return -2;
1249
1250 if (!target_running ())
1251 return -1;
1252
1253 /* Grab the correct annex. */
1254 document = get_features_xml (annex);
1255 if (document == NULL)
1256 return -1;
1257
1258 total_len = strlen (document);
1259
1260 if (offset > total_len)
1261 return -1;
1262
1263 if (offset + len > total_len)
1264 len = total_len - offset;
1265
1266 memcpy (readbuf, document + offset, len);
1267 return len;
1268 }
1269
1270 /* Worker routine for handle_qxfer_libraries.
1271 Add to the length pointed to by ARG a conservative estimate of the
1272 length needed to transmit the file name of INF. */
1273
1274 static void
1275 accumulate_file_name_length (struct inferior_list_entry *inf, void *arg)
1276 {
1277 struct dll_info *dll = (struct dll_info *) inf;
1278 unsigned int *total_len = arg;
1279
1280 /* Over-estimate the necessary memory. Assume that every character
1281 in the library name must be escaped. */
1282 *total_len += 128 + 6 * strlen (dll->name);
1283 }
1284
1285 /* Worker routine for handle_qxfer_libraries.
1286 Emit the XML to describe the library in INF. */
1287
1288 static void
1289 emit_dll_description (struct inferior_list_entry *inf, void *arg)
1290 {
1291 struct dll_info *dll = (struct dll_info *) inf;
1292 char **p_ptr = arg;
1293 char *p = *p_ptr;
1294 char *name;
1295
1296 strcpy (p, " <library name=\"");
1297 p = p + strlen (p);
1298 name = xml_escape_text (dll->name);
1299 strcpy (p, name);
1300 free (name);
1301 p = p + strlen (p);
1302 strcpy (p, "\"><segment address=\"");
1303 p = p + strlen (p);
1304 sprintf (p, "0x%lx", (long) dll->base_addr);
1305 p = p + strlen (p);
1306 strcpy (p, "\"/></library>\n");
1307 p = p + strlen (p);
1308
1309 *p_ptr = p;
1310 }
1311
1312 /* Handle qXfer:libraries:read. */
1313
1314 static int
1315 handle_qxfer_libraries (const char *annex,
1316 gdb_byte *readbuf, const gdb_byte *writebuf,
1317 ULONGEST offset, LONGEST len)
1318 {
1319 unsigned int total_len;
1320 char *document, *p;
1321
1322 if (writebuf != NULL)
1323 return -2;
1324
1325 if (annex[0] != '\0' || current_thread == NULL)
1326 return -1;
1327
1328 total_len = 64;
1329 for_each_inferior_with_data (&all_dlls, accumulate_file_name_length,
1330 &total_len);
1331
1332 document = malloc (total_len);
1333 if (document == NULL)
1334 return -1;
1335
1336 strcpy (document, "<library-list version=\"1.0\">\n");
1337 p = document + strlen (document);
1338
1339 for_each_inferior_with_data (&all_dlls, emit_dll_description, &p);
1340
1341 strcpy (p, "</library-list>\n");
1342
1343 total_len = strlen (document);
1344
1345 if (offset > total_len)
1346 {
1347 free (document);
1348 return -1;
1349 }
1350
1351 if (offset + len > total_len)
1352 len = total_len - offset;
1353
1354 memcpy (readbuf, document + offset, len);
1355 free (document);
1356 return len;
1357 }
1358
1359 /* Handle qXfer:libraries-svr4:read. */
1360
1361 static int
1362 handle_qxfer_libraries_svr4 (const char *annex,
1363 gdb_byte *readbuf, const gdb_byte *writebuf,
1364 ULONGEST offset, LONGEST len)
1365 {
1366 if (writebuf != NULL)
1367 return -2;
1368
1369 if (current_thread == NULL || the_target->qxfer_libraries_svr4 == NULL)
1370 return -1;
1371
1372 return the_target->qxfer_libraries_svr4 (annex, readbuf, writebuf, offset, len);
1373 }
1374
1375 /* Handle qXfer:osadata:read. */
1376
1377 static int
1378 handle_qxfer_osdata (const char *annex,
1379 gdb_byte *readbuf, const gdb_byte *writebuf,
1380 ULONGEST offset, LONGEST len)
1381 {
1382 if (the_target->qxfer_osdata == NULL || writebuf != NULL)
1383 return -2;
1384
1385 return (*the_target->qxfer_osdata) (annex, readbuf, NULL, offset, len);
1386 }
1387
1388 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1389
1390 static int
1391 handle_qxfer_siginfo (const char *annex,
1392 gdb_byte *readbuf, const gdb_byte *writebuf,
1393 ULONGEST offset, LONGEST len)
1394 {
1395 if (the_target->qxfer_siginfo == NULL)
1396 return -2;
1397
1398 if (annex[0] != '\0' || current_thread == NULL)
1399 return -1;
1400
1401 return (*the_target->qxfer_siginfo) (annex, readbuf, writebuf, offset, len);
1402 }
1403
1404 /* Handle qXfer:spu:read and qXfer:spu:write. */
1405
1406 static int
1407 handle_qxfer_spu (const char *annex,
1408 gdb_byte *readbuf, const gdb_byte *writebuf,
1409 ULONGEST offset, LONGEST len)
1410 {
1411 if (the_target->qxfer_spu == NULL)
1412 return -2;
1413
1414 if (current_thread == NULL)
1415 return -1;
1416
1417 return (*the_target->qxfer_spu) (annex, readbuf, writebuf, offset, len);
1418 }
1419
1420 /* Handle qXfer:statictrace:read. */
1421
1422 static int
1423 handle_qxfer_statictrace (const char *annex,
1424 gdb_byte *readbuf, const gdb_byte *writebuf,
1425 ULONGEST offset, LONGEST len)
1426 {
1427 ULONGEST nbytes;
1428
1429 if (writebuf != NULL)
1430 return -2;
1431
1432 if (annex[0] != '\0' || current_thread == NULL || current_traceframe == -1)
1433 return -1;
1434
1435 if (traceframe_read_sdata (current_traceframe, offset,
1436 readbuf, len, &nbytes))
1437 return -1;
1438 return nbytes;
1439 }
1440
1441 /* Helper for handle_qxfer_threads_proper.
1442 Emit the XML to describe the thread of INF. */
1443
1444 static void
1445 handle_qxfer_threads_worker (struct inferior_list_entry *inf, void *arg)
1446 {
1447 struct thread_info *thread = (struct thread_info *) inf;
1448 struct buffer *buffer = arg;
1449 ptid_t ptid = thread_to_gdb_id (thread);
1450 char ptid_s[100];
1451 int core = target_core_of_thread (ptid);
1452 char core_s[21];
1453
1454 write_ptid (ptid_s, ptid);
1455
1456 if (core != -1)
1457 {
1458 sprintf (core_s, "%d", core);
1459 buffer_xml_printf (buffer, "<thread id=\"%s\" core=\"%s\"/>\n",
1460 ptid_s, core_s);
1461 }
1462 else
1463 {
1464 buffer_xml_printf (buffer, "<thread id=\"%s\"/>\n",
1465 ptid_s);
1466 }
1467 }
1468
1469 /* Helper for handle_qxfer_threads. */
1470
1471 static void
1472 handle_qxfer_threads_proper (struct buffer *buffer)
1473 {
1474 buffer_grow_str (buffer, "<threads>\n");
1475
1476 for_each_inferior_with_data (&all_threads, handle_qxfer_threads_worker,
1477 buffer);
1478
1479 buffer_grow_str0 (buffer, "</threads>\n");
1480 }
1481
1482 /* Handle qXfer:threads:read. */
1483
1484 static int
1485 handle_qxfer_threads (const char *annex,
1486 gdb_byte *readbuf, const gdb_byte *writebuf,
1487 ULONGEST offset, LONGEST len)
1488 {
1489 static char *result = 0;
1490 static unsigned int result_length = 0;
1491
1492 if (writebuf != NULL)
1493 return -2;
1494
1495 if (annex[0] != '\0')
1496 return -1;
1497
1498 if (offset == 0)
1499 {
1500 struct buffer buffer;
1501 /* When asked for data at offset 0, generate everything and store into
1502 'result'. Successive reads will be served off 'result'. */
1503 if (result)
1504 free (result);
1505
1506 buffer_init (&buffer);
1507
1508 handle_qxfer_threads_proper (&buffer);
1509
1510 result = buffer_finish (&buffer);
1511 result_length = strlen (result);
1512 buffer_free (&buffer);
1513 }
1514
1515 if (offset >= result_length)
1516 {
1517 /* We're out of data. */
1518 free (result);
1519 result = NULL;
1520 result_length = 0;
1521 return 0;
1522 }
1523
1524 if (len > result_length - offset)
1525 len = result_length - offset;
1526
1527 memcpy (readbuf, result + offset, len);
1528
1529 return len;
1530 }
1531
1532 /* Handle qXfer:traceframe-info:read. */
1533
1534 static int
1535 handle_qxfer_traceframe_info (const char *annex,
1536 gdb_byte *readbuf, const gdb_byte *writebuf,
1537 ULONGEST offset, LONGEST len)
1538 {
1539 static char *result = 0;
1540 static unsigned int result_length = 0;
1541
1542 if (writebuf != NULL)
1543 return -2;
1544
1545 if (!target_running () || annex[0] != '\0' || current_traceframe == -1)
1546 return -1;
1547
1548 if (offset == 0)
1549 {
1550 struct buffer buffer;
1551
1552 /* When asked for data at offset 0, generate everything and
1553 store into 'result'. Successive reads will be served off
1554 'result'. */
1555 free (result);
1556
1557 buffer_init (&buffer);
1558
1559 traceframe_read_info (current_traceframe, &buffer);
1560
1561 result = buffer_finish (&buffer);
1562 result_length = strlen (result);
1563 buffer_free (&buffer);
1564 }
1565
1566 if (offset >= result_length)
1567 {
1568 /* We're out of data. */
1569 free (result);
1570 result = NULL;
1571 result_length = 0;
1572 return 0;
1573 }
1574
1575 if (len > result_length - offset)
1576 len = result_length - offset;
1577
1578 memcpy (readbuf, result + offset, len);
1579 return len;
1580 }
1581
1582 /* Handle qXfer:fdpic:read. */
1583
1584 static int
1585 handle_qxfer_fdpic (const char *annex, gdb_byte *readbuf,
1586 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
1587 {
1588 if (the_target->read_loadmap == NULL)
1589 return -2;
1590
1591 if (current_thread == NULL)
1592 return -1;
1593
1594 return (*the_target->read_loadmap) (annex, offset, readbuf, len);
1595 }
1596
1597 /* Handle qXfer:btrace:read. */
1598
1599 static int
1600 handle_qxfer_btrace (const char *annex,
1601 gdb_byte *readbuf, const gdb_byte *writebuf,
1602 ULONGEST offset, LONGEST len)
1603 {
1604 static struct buffer cache;
1605 struct thread_info *thread;
1606 int type, result;
1607
1608 if (the_target->read_btrace == NULL || writebuf != NULL)
1609 return -2;
1610
1611 if (ptid_equal (general_thread, null_ptid)
1612 || ptid_equal (general_thread, minus_one_ptid))
1613 {
1614 strcpy (own_buf, "E.Must select a single thread.");
1615 return -3;
1616 }
1617
1618 thread = find_thread_ptid (general_thread);
1619 if (thread == NULL)
1620 {
1621 strcpy (own_buf, "E.No such thread.");
1622 return -3;
1623 }
1624
1625 if (thread->btrace == NULL)
1626 {
1627 strcpy (own_buf, "E.Btrace not enabled.");
1628 return -3;
1629 }
1630
1631 if (strcmp (annex, "all") == 0)
1632 type = BTRACE_READ_ALL;
1633 else if (strcmp (annex, "new") == 0)
1634 type = BTRACE_READ_NEW;
1635 else if (strcmp (annex, "delta") == 0)
1636 type = BTRACE_READ_DELTA;
1637 else
1638 {
1639 strcpy (own_buf, "E.Bad annex.");
1640 return -3;
1641 }
1642
1643 if (offset == 0)
1644 {
1645 buffer_free (&cache);
1646
1647 result = target_read_btrace (thread->btrace, &cache, type);
1648 if (result != 0)
1649 {
1650 memcpy (own_buf, cache.buffer, cache.used_size);
1651 return -3;
1652 }
1653 }
1654 else if (offset > cache.used_size)
1655 {
1656 buffer_free (&cache);
1657 return -3;
1658 }
1659
1660 if (len > cache.used_size - offset)
1661 len = cache.used_size - offset;
1662
1663 memcpy (readbuf, cache.buffer + offset, len);
1664
1665 return len;
1666 }
1667
1668 /* Handle qXfer:btrace-conf:read. */
1669
1670 static int
1671 handle_qxfer_btrace_conf (const char *annex,
1672 gdb_byte *readbuf, const gdb_byte *writebuf,
1673 ULONGEST offset, LONGEST len)
1674 {
1675 static struct buffer cache;
1676 struct thread_info *thread;
1677 int result;
1678
1679 if (the_target->read_btrace_conf == NULL || writebuf != NULL)
1680 return -2;
1681
1682 if (annex[0] != '\0')
1683 return -1;
1684
1685 if (ptid_equal (general_thread, null_ptid)
1686 || ptid_equal (general_thread, minus_one_ptid))
1687 {
1688 strcpy (own_buf, "E.Must select a single thread.");
1689 return -3;
1690 }
1691
1692 thread = find_thread_ptid (general_thread);
1693 if (thread == NULL)
1694 {
1695 strcpy (own_buf, "E.No such thread.");
1696 return -3;
1697 }
1698
1699 if (thread->btrace == NULL)
1700 {
1701 strcpy (own_buf, "E.Btrace not enabled.");
1702 return -3;
1703 }
1704
1705 if (offset == 0)
1706 {
1707 buffer_free (&cache);
1708
1709 result = target_read_btrace_conf (thread->btrace, &cache);
1710 if (result != 0)
1711 {
1712 memcpy (own_buf, cache.buffer, cache.used_size);
1713 return -3;
1714 }
1715 }
1716 else if (offset > cache.used_size)
1717 {
1718 buffer_free (&cache);
1719 return -3;
1720 }
1721
1722 if (len > cache.used_size - offset)
1723 len = cache.used_size - offset;
1724
1725 memcpy (readbuf, cache.buffer + offset, len);
1726
1727 return len;
1728 }
1729
1730 static const struct qxfer qxfer_packets[] =
1731 {
1732 { "auxv", handle_qxfer_auxv },
1733 { "btrace", handle_qxfer_btrace },
1734 { "btrace-conf", handle_qxfer_btrace_conf },
1735 { "exec-file", handle_qxfer_exec_file},
1736 { "fdpic", handle_qxfer_fdpic},
1737 { "features", handle_qxfer_features },
1738 { "libraries", handle_qxfer_libraries },
1739 { "libraries-svr4", handle_qxfer_libraries_svr4 },
1740 { "osdata", handle_qxfer_osdata },
1741 { "siginfo", handle_qxfer_siginfo },
1742 { "spu", handle_qxfer_spu },
1743 { "statictrace", handle_qxfer_statictrace },
1744 { "threads", handle_qxfer_threads },
1745 { "traceframe-info", handle_qxfer_traceframe_info },
1746 };
1747
1748 static int
1749 handle_qxfer (char *own_buf, int packet_len, int *new_packet_len_p)
1750 {
1751 int i;
1752 char *object;
1753 char *rw;
1754 char *annex;
1755 char *offset;
1756
1757 if (!startswith (own_buf, "qXfer:"))
1758 return 0;
1759
1760 /* Grab the object, r/w and annex. */
1761 if (decode_xfer (own_buf + 6, &object, &rw, &annex, &offset) < 0)
1762 {
1763 write_enn (own_buf);
1764 return 1;
1765 }
1766
1767 for (i = 0;
1768 i < sizeof (qxfer_packets) / sizeof (qxfer_packets[0]);
1769 i++)
1770 {
1771 const struct qxfer *q = &qxfer_packets[i];
1772
1773 if (strcmp (object, q->object) == 0)
1774 {
1775 if (strcmp (rw, "read") == 0)
1776 {
1777 unsigned char *data;
1778 int n;
1779 CORE_ADDR ofs;
1780 unsigned int len;
1781
1782 /* Grab the offset and length. */
1783 if (decode_xfer_read (offset, &ofs, &len) < 0)
1784 {
1785 write_enn (own_buf);
1786 return 1;
1787 }
1788
1789 /* Read one extra byte, as an indicator of whether there is
1790 more. */
1791 if (len > PBUFSIZ - 2)
1792 len = PBUFSIZ - 2;
1793 data = malloc (len + 1);
1794 if (data == NULL)
1795 {
1796 write_enn (own_buf);
1797 return 1;
1798 }
1799 n = (*q->xfer) (annex, data, NULL, ofs, len + 1);
1800 if (n == -2)
1801 {
1802 free (data);
1803 return 0;
1804 }
1805 else if (n == -3)
1806 {
1807 /* Preserve error message. */
1808 }
1809 else if (n < 0)
1810 write_enn (own_buf);
1811 else if (n > len)
1812 *new_packet_len_p = write_qxfer_response (own_buf, data, len, 1);
1813 else
1814 *new_packet_len_p = write_qxfer_response (own_buf, data, n, 0);
1815
1816 free (data);
1817 return 1;
1818 }
1819 else if (strcmp (rw, "write") == 0)
1820 {
1821 int n;
1822 unsigned int len;
1823 CORE_ADDR ofs;
1824 unsigned char *data;
1825
1826 strcpy (own_buf, "E00");
1827 data = malloc (packet_len - (offset - own_buf));
1828 if (data == NULL)
1829 {
1830 write_enn (own_buf);
1831 return 1;
1832 }
1833 if (decode_xfer_write (offset, packet_len - (offset - own_buf),
1834 &ofs, &len, data) < 0)
1835 {
1836 free (data);
1837 write_enn (own_buf);
1838 return 1;
1839 }
1840
1841 n = (*q->xfer) (annex, NULL, data, ofs, len);
1842 if (n == -2)
1843 {
1844 free (data);
1845 return 0;
1846 }
1847 else if (n == -3)
1848 {
1849 /* Preserve error message. */
1850 }
1851 else if (n < 0)
1852 write_enn (own_buf);
1853 else
1854 sprintf (own_buf, "%x", n);
1855
1856 free (data);
1857 return 1;
1858 }
1859
1860 return 0;
1861 }
1862 }
1863
1864 return 0;
1865 }
1866
1867 /* Table used by the crc32 function to calcuate the checksum. */
1868
1869 static unsigned int crc32_table[256] =
1870 {0, 0};
1871
1872 /* Compute 32 bit CRC from inferior memory.
1873
1874 On success, return 32 bit CRC.
1875 On failure, return (unsigned long long) -1. */
1876
1877 static unsigned long long
1878 crc32 (CORE_ADDR base, int len, unsigned int crc)
1879 {
1880 if (!crc32_table[1])
1881 {
1882 /* Initialize the CRC table and the decoding table. */
1883 int i, j;
1884 unsigned int c;
1885
1886 for (i = 0; i < 256; i++)
1887 {
1888 for (c = i << 24, j = 8; j > 0; --j)
1889 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
1890 crc32_table[i] = c;
1891 }
1892 }
1893
1894 while (len--)
1895 {
1896 unsigned char byte = 0;
1897
1898 /* Return failure if memory read fails. */
1899 if (read_inferior_memory (base, &byte, 1) != 0)
1900 return (unsigned long long) -1;
1901
1902 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ byte) & 255];
1903 base++;
1904 }
1905 return (unsigned long long) crc;
1906 }
1907
1908 /* Add supported btrace packets to BUF. */
1909
1910 static void
1911 supported_btrace_packets (char *buf)
1912 {
1913 int btrace_supported = 0;
1914
1915 if (target_supports_btrace (BTRACE_FORMAT_BTS))
1916 {
1917 strcat (buf, ";Qbtrace:bts+");
1918 strcat (buf, ";Qbtrace-conf:bts:size+");
1919
1920 btrace_supported = 1;
1921 }
1922
1923 if (target_supports_btrace (BTRACE_FORMAT_PT))
1924 {
1925 strcat (buf, ";Qbtrace:pt+");
1926 strcat (buf, ";Qbtrace-conf:pt:size+");
1927
1928 btrace_supported = 1;
1929 }
1930
1931 if (!btrace_supported)
1932 return;
1933
1934 strcat (buf, ";Qbtrace:off+");
1935 strcat (buf, ";qXfer:btrace:read+");
1936 strcat (buf, ";qXfer:btrace-conf:read+");
1937 }
1938
1939 /* Handle all of the extended 'q' packets. */
1940
1941 void
1942 handle_query (char *own_buf, int packet_len, int *new_packet_len_p)
1943 {
1944 static struct inferior_list_entry *thread_ptr;
1945
1946 /* Reply the current thread id. */
1947 if (strcmp ("qC", own_buf) == 0 && !disable_packet_qC)
1948 {
1949 ptid_t gdb_id;
1950 require_running (own_buf);
1951
1952 if (!ptid_equal (general_thread, null_ptid)
1953 && !ptid_equal (general_thread, minus_one_ptid))
1954 gdb_id = general_thread;
1955 else
1956 {
1957 thread_ptr = get_first_inferior (&all_threads);
1958 gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
1959 }
1960
1961 sprintf (own_buf, "QC");
1962 own_buf += 2;
1963 write_ptid (own_buf, gdb_id);
1964 return;
1965 }
1966
1967 if (strcmp ("qSymbol::", own_buf) == 0)
1968 {
1969 /* GDB is suggesting new symbols have been loaded. This may
1970 mean a new shared library has been detected as loaded, so
1971 take the opportunity to check if breakpoints we think are
1972 inserted, still are. Note that it isn't guaranteed that
1973 we'll see this when a shared library is loaded, and nor will
1974 we see this for unloads (although breakpoints in unloaded
1975 libraries shouldn't trigger), as GDB may not find symbols for
1976 the library at all. We also re-validate breakpoints when we
1977 see a second GDB breakpoint for the same address, and or when
1978 we access breakpoint shadows. */
1979 validate_breakpoints ();
1980
1981 if (target_supports_tracepoints ())
1982 tracepoint_look_up_symbols ();
1983
1984 if (current_thread != NULL && the_target->look_up_symbols != NULL)
1985 (*the_target->look_up_symbols) ();
1986
1987 strcpy (own_buf, "OK");
1988 return;
1989 }
1990
1991 if (!disable_packet_qfThreadInfo)
1992 {
1993 if (strcmp ("qfThreadInfo", own_buf) == 0)
1994 {
1995 ptid_t gdb_id;
1996
1997 require_running (own_buf);
1998 thread_ptr = get_first_inferior (&all_threads);
1999
2000 *own_buf++ = 'm';
2001 gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
2002 write_ptid (own_buf, gdb_id);
2003 thread_ptr = thread_ptr->next;
2004 return;
2005 }
2006
2007 if (strcmp ("qsThreadInfo", own_buf) == 0)
2008 {
2009 ptid_t gdb_id;
2010
2011 require_running (own_buf);
2012 if (thread_ptr != NULL)
2013 {
2014 *own_buf++ = 'm';
2015 gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
2016 write_ptid (own_buf, gdb_id);
2017 thread_ptr = thread_ptr->next;
2018 return;
2019 }
2020 else
2021 {
2022 sprintf (own_buf, "l");
2023 return;
2024 }
2025 }
2026 }
2027
2028 if (the_target->read_offsets != NULL
2029 && strcmp ("qOffsets", own_buf) == 0)
2030 {
2031 CORE_ADDR text, data;
2032
2033 require_running (own_buf);
2034 if (the_target->read_offsets (&text, &data))
2035 sprintf (own_buf, "Text=%lX;Data=%lX;Bss=%lX",
2036 (long)text, (long)data, (long)data);
2037 else
2038 write_enn (own_buf);
2039
2040 return;
2041 }
2042
2043 /* Protocol features query. */
2044 if (startswith (own_buf, "qSupported")
2045 && (own_buf[10] == ':' || own_buf[10] == '\0'))
2046 {
2047 char *p = &own_buf[10];
2048 int gdb_supports_qRelocInsn = 0;
2049
2050 /* Start processing qSupported packet. */
2051 target_process_qsupported (NULL);
2052
2053 /* Process each feature being provided by GDB. The first
2054 feature will follow a ':', and latter features will follow
2055 ';'. */
2056 if (*p == ':')
2057 {
2058 char **qsupported = NULL;
2059 int count = 0;
2060 int i;
2061
2062 /* Two passes, to avoid nested strtok calls in
2063 target_process_qsupported. */
2064 for (p = strtok (p + 1, ";");
2065 p != NULL;
2066 p = strtok (NULL, ";"))
2067 {
2068 count++;
2069 qsupported = xrealloc (qsupported, count * sizeof (char *));
2070 qsupported[count - 1] = xstrdup (p);
2071 }
2072
2073 for (i = 0; i < count; i++)
2074 {
2075 p = qsupported[i];
2076 if (strcmp (p, "multiprocess+") == 0)
2077 {
2078 /* GDB supports and wants multi-process support if
2079 possible. */
2080 if (target_supports_multi_process ())
2081 multi_process = 1;
2082 }
2083 else if (strcmp (p, "qRelocInsn+") == 0)
2084 {
2085 /* GDB supports relocate instruction requests. */
2086 gdb_supports_qRelocInsn = 1;
2087 }
2088 else if (strcmp (p, "swbreak+") == 0)
2089 {
2090 /* GDB wants us to report whether a trap is caused
2091 by a software breakpoint and for us to handle PC
2092 adjustment if necessary on this target. */
2093 if (target_supports_stopped_by_sw_breakpoint ())
2094 swbreak_feature = 1;
2095 }
2096 else if (strcmp (p, "hwbreak+") == 0)
2097 {
2098 /* GDB wants us to report whether a trap is caused
2099 by a hardware breakpoint. */
2100 if (target_supports_stopped_by_hw_breakpoint ())
2101 hwbreak_feature = 1;
2102 }
2103 else if (strcmp (p, "fork-events+") == 0)
2104 {
2105 /* GDB supports and wants fork events if possible. */
2106 if (target_supports_fork_events ())
2107 report_fork_events = 1;
2108 }
2109 else if (strcmp (p, "vfork-events+") == 0)
2110 {
2111 /* GDB supports and wants vfork events if possible. */
2112 if (target_supports_vfork_events ())
2113 report_vfork_events = 1;
2114 }
2115 if (strcmp (p, "exec-events+") == 0)
2116 {
2117 /* GDB supports and wants exec events if possible. */
2118 if (target_supports_exec_events ())
2119 report_exec_events = 1;
2120 }
2121 else
2122 target_process_qsupported (p);
2123
2124 free (p);
2125 }
2126
2127 free (qsupported);
2128 }
2129
2130 sprintf (own_buf,
2131 "PacketSize=%x;QPassSignals+;QProgramSignals+",
2132 PBUFSIZ - 1);
2133
2134 if (the_target->qxfer_libraries_svr4 != NULL)
2135 strcat (own_buf, ";qXfer:libraries-svr4:read+"
2136 ";augmented-libraries-svr4-read+");
2137 else
2138 {
2139 /* We do not have any hook to indicate whether the non-SVR4 target
2140 backend supports qXfer:libraries:read, so always report it. */
2141 strcat (own_buf, ";qXfer:libraries:read+");
2142 }
2143
2144 if (the_target->read_auxv != NULL)
2145 strcat (own_buf, ";qXfer:auxv:read+");
2146
2147 if (the_target->qxfer_spu != NULL)
2148 strcat (own_buf, ";qXfer:spu:read+;qXfer:spu:write+");
2149
2150 if (the_target->qxfer_siginfo != NULL)
2151 strcat (own_buf, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2152
2153 if (the_target->read_loadmap != NULL)
2154 strcat (own_buf, ";qXfer:fdpic:read+");
2155
2156 /* We always report qXfer:features:read, as targets may
2157 install XML files on a subsequent call to arch_setup.
2158 If we reported to GDB on startup that we don't support
2159 qXfer:feature:read at all, we will never be re-queried. */
2160 strcat (own_buf, ";qXfer:features:read+");
2161
2162 if (transport_is_reliable)
2163 strcat (own_buf, ";QStartNoAckMode+");
2164
2165 if (the_target->qxfer_osdata != NULL)
2166 strcat (own_buf, ";qXfer:osdata:read+");
2167
2168 if (target_supports_multi_process ())
2169 strcat (own_buf, ";multiprocess+");
2170
2171 if (target_supports_fork_events ())
2172 strcat (own_buf, ";fork-events+");
2173
2174 if (target_supports_vfork_events ())
2175 strcat (own_buf, ";vfork-events+");
2176
2177 if (target_supports_exec_events ())
2178 strcat (own_buf, ";exec-events+");
2179
2180 if (target_supports_non_stop ())
2181 strcat (own_buf, ";QNonStop+");
2182
2183 if (target_supports_disable_randomization ())
2184 strcat (own_buf, ";QDisableRandomization+");
2185
2186 strcat (own_buf, ";qXfer:threads:read+");
2187
2188 if (target_supports_tracepoints ())
2189 {
2190 strcat (own_buf, ";ConditionalTracepoints+");
2191 strcat (own_buf, ";TraceStateVariables+");
2192 strcat (own_buf, ";TracepointSource+");
2193 strcat (own_buf, ";DisconnectedTracing+");
2194 if (gdb_supports_qRelocInsn && target_supports_fast_tracepoints ())
2195 strcat (own_buf, ";FastTracepoints+");
2196 strcat (own_buf, ";StaticTracepoints+");
2197 strcat (own_buf, ";InstallInTrace+");
2198 strcat (own_buf, ";qXfer:statictrace:read+");
2199 strcat (own_buf, ";qXfer:traceframe-info:read+");
2200 strcat (own_buf, ";EnableDisableTracepoints+");
2201 strcat (own_buf, ";QTBuffer:size+");
2202 strcat (own_buf, ";tracenz+");
2203 }
2204
2205 /* Support target-side breakpoint conditions and commands. */
2206 if (target_supports_conditional_breakpoints ())
2207 strcat (own_buf, ";ConditionalBreakpoints+");
2208 strcat (own_buf, ";BreakpointCommands+");
2209
2210 if (target_supports_agent ())
2211 strcat (own_buf, ";QAgent+");
2212
2213 supported_btrace_packets (own_buf);
2214
2215 if (target_supports_stopped_by_sw_breakpoint ())
2216 strcat (own_buf, ";swbreak+");
2217
2218 if (target_supports_stopped_by_hw_breakpoint ())
2219 strcat (own_buf, ";hwbreak+");
2220
2221 if (the_target->pid_to_exec_file != NULL)
2222 strcat (own_buf, ";qXfer:exec-file:read+");
2223
2224 /* Reinitialize components as needed for the new connection. */
2225 hostio_handle_new_gdb_connection ();
2226 target_handle_new_gdb_connection ();
2227
2228 return;
2229 }
2230
2231 /* Thread-local storage support. */
2232 if (the_target->get_tls_address != NULL
2233 && startswith (own_buf, "qGetTLSAddr:"))
2234 {
2235 char *p = own_buf + 12;
2236 CORE_ADDR parts[2], address = 0;
2237 int i, err;
2238 ptid_t ptid = null_ptid;
2239
2240 require_running (own_buf);
2241
2242 for (i = 0; i < 3; i++)
2243 {
2244 char *p2;
2245 int len;
2246
2247 if (p == NULL)
2248 break;
2249
2250 p2 = strchr (p, ',');
2251 if (p2)
2252 {
2253 len = p2 - p;
2254 p2++;
2255 }
2256 else
2257 {
2258 len = strlen (p);
2259 p2 = NULL;
2260 }
2261
2262 if (i == 0)
2263 ptid = read_ptid (p, NULL);
2264 else
2265 decode_address (&parts[i - 1], p, len);
2266 p = p2;
2267 }
2268
2269 if (p != NULL || i < 3)
2270 err = 1;
2271 else
2272 {
2273 struct thread_info *thread = find_thread_ptid (ptid);
2274
2275 if (thread == NULL)
2276 err = 2;
2277 else
2278 err = the_target->get_tls_address (thread, parts[0], parts[1],
2279 &address);
2280 }
2281
2282 if (err == 0)
2283 {
2284 strcpy (own_buf, paddress(address));
2285 return;
2286 }
2287 else if (err > 0)
2288 {
2289 write_enn (own_buf);
2290 return;
2291 }
2292
2293 /* Otherwise, pretend we do not understand this packet. */
2294 }
2295
2296 /* Windows OS Thread Information Block address support. */
2297 if (the_target->get_tib_address != NULL
2298 && startswith (own_buf, "qGetTIBAddr:"))
2299 {
2300 char *annex;
2301 int n;
2302 CORE_ADDR tlb;
2303 ptid_t ptid = read_ptid (own_buf + 12, &annex);
2304
2305 n = (*the_target->get_tib_address) (ptid, &tlb);
2306 if (n == 1)
2307 {
2308 strcpy (own_buf, paddress(tlb));
2309 return;
2310 }
2311 else if (n == 0)
2312 {
2313 write_enn (own_buf);
2314 return;
2315 }
2316 return;
2317 }
2318
2319 /* Handle "monitor" commands. */
2320 if (startswith (own_buf, "qRcmd,"))
2321 {
2322 char *mon = malloc (PBUFSIZ);
2323 int len = strlen (own_buf + 6);
2324
2325 if (mon == NULL)
2326 {
2327 write_enn (own_buf);
2328 return;
2329 }
2330
2331 if ((len % 2) != 0
2332 || hex2bin (own_buf + 6, (gdb_byte *) mon, len / 2) != len / 2)
2333 {
2334 write_enn (own_buf);
2335 free (mon);
2336 return;
2337 }
2338 mon[len / 2] = '\0';
2339
2340 write_ok (own_buf);
2341
2342 if (the_target->handle_monitor_command == NULL
2343 || (*the_target->handle_monitor_command) (mon) == 0)
2344 /* Default processing. */
2345 handle_monitor_command (mon, own_buf);
2346
2347 free (mon);
2348 return;
2349 }
2350
2351 if (startswith (own_buf, "qSearch:memory:"))
2352 {
2353 require_running (own_buf);
2354 handle_search_memory (own_buf, packet_len);
2355 return;
2356 }
2357
2358 if (strcmp (own_buf, "qAttached") == 0
2359 || startswith (own_buf, "qAttached:"))
2360 {
2361 struct process_info *process;
2362
2363 if (own_buf[sizeof ("qAttached") - 1])
2364 {
2365 int pid = strtoul (own_buf + sizeof ("qAttached:") - 1, NULL, 16);
2366 process = (struct process_info *)
2367 find_inferior_id (&all_processes, pid_to_ptid (pid));
2368 }
2369 else
2370 {
2371 require_running (own_buf);
2372 process = current_process ();
2373 }
2374
2375 if (process == NULL)
2376 {
2377 write_enn (own_buf);
2378 return;
2379 }
2380
2381 strcpy (own_buf, process->attached ? "1" : "0");
2382 return;
2383 }
2384
2385 if (startswith (own_buf, "qCRC:"))
2386 {
2387 /* CRC check (compare-section). */
2388 char *comma;
2389 ULONGEST base;
2390 int len;
2391 unsigned long long crc;
2392
2393 require_running (own_buf);
2394 comma = unpack_varlen_hex (own_buf + 5, &base);
2395 if (*comma++ != ',')
2396 {
2397 write_enn (own_buf);
2398 return;
2399 }
2400 len = strtoul (comma, NULL, 16);
2401 crc = crc32 (base, len, 0xffffffff);
2402 /* Check for memory failure. */
2403 if (crc == (unsigned long long) -1)
2404 {
2405 write_enn (own_buf);
2406 return;
2407 }
2408 sprintf (own_buf, "C%lx", (unsigned long) crc);
2409 return;
2410 }
2411
2412 if (handle_qxfer (own_buf, packet_len, new_packet_len_p))
2413 return;
2414
2415 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf))
2416 return;
2417
2418 /* Otherwise we didn't know what packet it was. Say we didn't
2419 understand it. */
2420 own_buf[0] = 0;
2421 }
2422
2423 static void gdb_wants_all_threads_stopped (void);
2424 static void resume (struct thread_resume *actions, size_t n);
2425
2426 /* The callback that is passed to visit_actioned_threads. */
2427 typedef int (visit_actioned_threads_callback_ftype)
2428 (const struct thread_resume *, struct thread_info *);
2429
2430 /* Struct to pass data to visit_actioned_threads. */
2431
2432 struct visit_actioned_threads_data
2433 {
2434 const struct thread_resume *actions;
2435 size_t num_actions;
2436 visit_actioned_threads_callback_ftype *callback;
2437 };
2438
2439 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
2440 true if CALLBACK returns true. Returns false if no matching thread
2441 is found or CALLBACK results false.
2442 Note: This function is itself a callback for find_inferior. */
2443
2444 static int
2445 visit_actioned_threads (struct inferior_list_entry *entry, void *datap)
2446 {
2447 struct visit_actioned_threads_data *data = datap;
2448 const struct thread_resume *actions = data->actions;
2449 size_t num_actions = data->num_actions;
2450 visit_actioned_threads_callback_ftype *callback = data->callback;
2451 size_t i;
2452
2453 for (i = 0; i < num_actions; i++)
2454 {
2455 const struct thread_resume *action = &actions[i];
2456
2457 if (ptid_equal (action->thread, minus_one_ptid)
2458 || ptid_equal (action->thread, entry->id)
2459 || ((ptid_get_pid (action->thread)
2460 == ptid_get_pid (entry->id))
2461 && ptid_get_lwp (action->thread) == -1))
2462 {
2463 struct thread_info *thread = (struct thread_info *) entry;
2464
2465 if ((*callback) (action, thread))
2466 return 1;
2467 }
2468 }
2469
2470 return 0;
2471 }
2472
2473 /* Callback for visit_actioned_threads. If the thread has a pending
2474 status to report, report it now. */
2475
2476 static int
2477 handle_pending_status (const struct thread_resume *resumption,
2478 struct thread_info *thread)
2479 {
2480 if (thread->status_pending_p)
2481 {
2482 thread->status_pending_p = 0;
2483
2484 last_status = thread->last_status;
2485 last_ptid = thread->entry.id;
2486 prepare_resume_reply (own_buf, last_ptid, &last_status);
2487 return 1;
2488 }
2489 return 0;
2490 }
2491
2492 /* Parse vCont packets. */
2493 void
2494 handle_v_cont (char *own_buf)
2495 {
2496 char *p, *q;
2497 int n = 0, i = 0;
2498 struct thread_resume *resume_info;
2499 struct thread_resume default_action = {{0}};
2500
2501 /* Count the number of semicolons in the packet. There should be one
2502 for every action. */
2503 p = &own_buf[5];
2504 while (p)
2505 {
2506 n++;
2507 p++;
2508 p = strchr (p, ';');
2509 }
2510
2511 resume_info = malloc (n * sizeof (resume_info[0]));
2512 if (resume_info == NULL)
2513 goto err;
2514
2515 p = &own_buf[5];
2516 while (*p)
2517 {
2518 p++;
2519
2520 memset (&resume_info[i], 0, sizeof resume_info[i]);
2521
2522 if (p[0] == 's' || p[0] == 'S')
2523 resume_info[i].kind = resume_step;
2524 else if (p[0] == 'r')
2525 resume_info[i].kind = resume_step;
2526 else if (p[0] == 'c' || p[0] == 'C')
2527 resume_info[i].kind = resume_continue;
2528 else if (p[0] == 't')
2529 resume_info[i].kind = resume_stop;
2530 else
2531 goto err;
2532
2533 if (p[0] == 'S' || p[0] == 'C')
2534 {
2535 int sig;
2536 sig = strtol (p + 1, &q, 16);
2537 if (p == q)
2538 goto err;
2539 p = q;
2540
2541 if (!gdb_signal_to_host_p (sig))
2542 goto err;
2543 resume_info[i].sig = gdb_signal_to_host (sig);
2544 }
2545 else if (p[0] == 'r')
2546 {
2547 ULONGEST addr;
2548
2549 p = unpack_varlen_hex (p + 1, &addr);
2550 resume_info[i].step_range_start = addr;
2551
2552 if (*p != ',')
2553 goto err;
2554
2555 p = unpack_varlen_hex (p + 1, &addr);
2556 resume_info[i].step_range_end = addr;
2557 }
2558 else
2559 {
2560 p = p + 1;
2561 }
2562
2563 if (p[0] == 0)
2564 {
2565 resume_info[i].thread = minus_one_ptid;
2566 default_action = resume_info[i];
2567
2568 /* Note: we don't increment i here, we'll overwrite this entry
2569 the next time through. */
2570 }
2571 else if (p[0] == ':')
2572 {
2573 ptid_t ptid = read_ptid (p + 1, &q);
2574
2575 if (p == q)
2576 goto err;
2577 p = q;
2578 if (p[0] != ';' && p[0] != 0)
2579 goto err;
2580
2581 resume_info[i].thread = ptid;
2582
2583 i++;
2584 }
2585 }
2586
2587 if (i < n)
2588 resume_info[i] = default_action;
2589
2590 resume (resume_info, n);
2591 free (resume_info);
2592 return;
2593
2594 err:
2595 write_enn (own_buf);
2596 free (resume_info);
2597 return;
2598 }
2599
2600 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
2601
2602 static void
2603 resume (struct thread_resume *actions, size_t num_actions)
2604 {
2605 if (!non_stop)
2606 {
2607 /* Check if among the threads that GDB wants actioned, there's
2608 one with a pending status to report. If so, skip actually
2609 resuming/stopping and report the pending event
2610 immediately. */
2611 struct visit_actioned_threads_data data;
2612
2613 data.actions = actions;
2614 data.num_actions = num_actions;
2615 data.callback = handle_pending_status;
2616 if (find_inferior (&all_threads, visit_actioned_threads, &data) != NULL)
2617 return;
2618
2619 enable_async_io ();
2620 }
2621
2622 (*the_target->resume) (actions, num_actions);
2623
2624 if (non_stop)
2625 write_ok (own_buf);
2626 else
2627 {
2628 last_ptid = mywait (minus_one_ptid, &last_status, 0, 1);
2629
2630 if (last_status.kind == TARGET_WAITKIND_NO_RESUMED)
2631 {
2632 /* No proper RSP support for this yet. At least return
2633 error. */
2634 sprintf (own_buf, "E.No unwaited-for children left.");
2635 disable_async_io ();
2636 return;
2637 }
2638
2639 if (last_status.kind != TARGET_WAITKIND_EXITED
2640 && last_status.kind != TARGET_WAITKIND_SIGNALLED
2641 && last_status.kind != TARGET_WAITKIND_NO_RESUMED)
2642 current_thread->last_status = last_status;
2643
2644 /* From the client's perspective, all-stop mode always stops all
2645 threads implicitly (and the target backend has already done
2646 so by now). Tag all threads as "want-stopped", so we don't
2647 resume them implicitly without the client telling us to. */
2648 gdb_wants_all_threads_stopped ();
2649 prepare_resume_reply (own_buf, last_ptid, &last_status);
2650 disable_async_io ();
2651
2652 if (last_status.kind == TARGET_WAITKIND_EXITED
2653 || last_status.kind == TARGET_WAITKIND_SIGNALLED)
2654 mourn_inferior (find_process_pid (ptid_get_pid (last_ptid)));
2655 }
2656 }
2657
2658 /* Attach to a new program. Return 1 if successful, 0 if failure. */
2659 int
2660 handle_v_attach (char *own_buf)
2661 {
2662 int pid;
2663
2664 pid = strtol (own_buf + 8, NULL, 16);
2665 if (pid != 0 && attach_inferior (pid) == 0)
2666 {
2667 /* Don't report shared library events after attaching, even if
2668 some libraries are preloaded. GDB will always poll the
2669 library list. Avoids the "stopped by shared library event"
2670 notice on the GDB side. */
2671 dlls_changed = 0;
2672
2673 if (non_stop)
2674 {
2675 /* In non-stop, we don't send a resume reply. Stop events
2676 will follow up using the normal notification
2677 mechanism. */
2678 write_ok (own_buf);
2679 }
2680 else
2681 prepare_resume_reply (own_buf, last_ptid, &last_status);
2682
2683 return 1;
2684 }
2685 else
2686 {
2687 write_enn (own_buf);
2688 return 0;
2689 }
2690 }
2691
2692 /* Run a new program. Return 1 if successful, 0 if failure. */
2693 static int
2694 handle_v_run (char *own_buf)
2695 {
2696 char *p, *next_p, **new_argv;
2697 int i, new_argc;
2698
2699 new_argc = 0;
2700 for (p = own_buf + strlen ("vRun;"); p && *p; p = strchr (p, ';'))
2701 {
2702 p++;
2703 new_argc++;
2704 }
2705
2706 new_argv = calloc (new_argc + 2, sizeof (char *));
2707 if (new_argv == NULL)
2708 {
2709 write_enn (own_buf);
2710 return 0;
2711 }
2712
2713 i = 0;
2714 for (p = own_buf + strlen ("vRun;"); *p; p = next_p)
2715 {
2716 next_p = strchr (p, ';');
2717 if (next_p == NULL)
2718 next_p = p + strlen (p);
2719
2720 if (i == 0 && p == next_p)
2721 new_argv[i] = NULL;
2722 else
2723 {
2724 /* FIXME: Fail request if out of memory instead of dying. */
2725 new_argv[i] = xmalloc (1 + (next_p - p) / 2);
2726 hex2bin (p, (gdb_byte *) new_argv[i], (next_p - p) / 2);
2727 new_argv[i][(next_p - p) / 2] = '\0';
2728 }
2729
2730 if (*next_p)
2731 next_p++;
2732 i++;
2733 }
2734 new_argv[i] = NULL;
2735
2736 if (new_argv[0] == NULL)
2737 {
2738 /* GDB didn't specify a program to run. Use the program from the
2739 last run with the new argument list. */
2740
2741 if (program_argv == NULL)
2742 {
2743 write_enn (own_buf);
2744 freeargv (new_argv);
2745 return 0;
2746 }
2747
2748 new_argv[0] = strdup (program_argv[0]);
2749 if (new_argv[0] == NULL)
2750 {
2751 write_enn (own_buf);
2752 freeargv (new_argv);
2753 return 0;
2754 }
2755 }
2756
2757 /* Free the old argv and install the new one. */
2758 freeargv (program_argv);
2759 program_argv = new_argv;
2760
2761 start_inferior (program_argv);
2762 if (last_status.kind == TARGET_WAITKIND_STOPPED)
2763 {
2764 prepare_resume_reply (own_buf, last_ptid, &last_status);
2765
2766 /* In non-stop, sending a resume reply doesn't set the general
2767 thread, but GDB assumes a vRun sets it (this is so GDB can
2768 query which is the main thread of the new inferior. */
2769 if (non_stop)
2770 general_thread = last_ptid;
2771
2772 return 1;
2773 }
2774 else
2775 {
2776 write_enn (own_buf);
2777 return 0;
2778 }
2779 }
2780
2781 /* Kill process. Return 1 if successful, 0 if failure. */
2782 int
2783 handle_v_kill (char *own_buf)
2784 {
2785 int pid;
2786 char *p = &own_buf[6];
2787 if (multi_process)
2788 pid = strtol (p, NULL, 16);
2789 else
2790 pid = signal_pid;
2791 if (pid != 0 && kill_inferior (pid) == 0)
2792 {
2793 last_status.kind = TARGET_WAITKIND_SIGNALLED;
2794 last_status.value.sig = GDB_SIGNAL_KILL;
2795 last_ptid = pid_to_ptid (pid);
2796 discard_queued_stop_replies (last_ptid);
2797 write_ok (own_buf);
2798 return 1;
2799 }
2800 else
2801 {
2802 write_enn (own_buf);
2803 return 0;
2804 }
2805 }
2806
2807 /* Handle all of the extended 'v' packets. */
2808 void
2809 handle_v_requests (char *own_buf, int packet_len, int *new_packet_len)
2810 {
2811 if (!disable_packet_vCont)
2812 {
2813 if (startswith (own_buf, "vCont;"))
2814 {
2815 require_running (own_buf);
2816 handle_v_cont (own_buf);
2817 return;
2818 }
2819
2820 if (startswith (own_buf, "vCont?"))
2821 {
2822 strcpy (own_buf, "vCont;c;C;s;S;t");
2823 if (target_supports_range_stepping ())
2824 {
2825 own_buf = own_buf + strlen (own_buf);
2826 strcpy (own_buf, ";r");
2827 }
2828 return;
2829 }
2830 }
2831
2832 if (startswith (own_buf, "vFile:")
2833 && handle_vFile (own_buf, packet_len, new_packet_len))
2834 return;
2835
2836 if (startswith (own_buf, "vAttach;"))
2837 {
2838 if ((!extended_protocol || !multi_process) && target_running ())
2839 {
2840 fprintf (stderr, "Already debugging a process\n");
2841 write_enn (own_buf);
2842 return;
2843 }
2844 handle_v_attach (own_buf);
2845 return;
2846 }
2847
2848 if (startswith (own_buf, "vRun;"))
2849 {
2850 if ((!extended_protocol || !multi_process) && target_running ())
2851 {
2852 fprintf (stderr, "Already debugging a process\n");
2853 write_enn (own_buf);
2854 return;
2855 }
2856 handle_v_run (own_buf);
2857 return;
2858 }
2859
2860 if (startswith (own_buf, "vKill;"))
2861 {
2862 if (!target_running ())
2863 {
2864 fprintf (stderr, "No process to kill\n");
2865 write_enn (own_buf);
2866 return;
2867 }
2868 handle_v_kill (own_buf);
2869 return;
2870 }
2871
2872 if (handle_notif_ack (own_buf, packet_len))
2873 return;
2874
2875 /* Otherwise we didn't know what packet it was. Say we didn't
2876 understand it. */
2877 own_buf[0] = 0;
2878 return;
2879 }
2880
2881 /* Resume thread and wait for another event. In non-stop mode,
2882 don't really wait here, but return immediatelly to the event
2883 loop. */
2884 static void
2885 myresume (char *own_buf, int step, int sig)
2886 {
2887 struct thread_resume resume_info[2];
2888 int n = 0;
2889 int valid_cont_thread;
2890
2891 valid_cont_thread = (!ptid_equal (cont_thread, null_ptid)
2892 && !ptid_equal (cont_thread, minus_one_ptid));
2893
2894 if (step || sig || valid_cont_thread)
2895 {
2896 resume_info[0].thread = current_ptid;
2897 if (step)
2898 resume_info[0].kind = resume_step;
2899 else
2900 resume_info[0].kind = resume_continue;
2901 resume_info[0].sig = sig;
2902 n++;
2903 }
2904
2905 if (!valid_cont_thread)
2906 {
2907 resume_info[n].thread = minus_one_ptid;
2908 resume_info[n].kind = resume_continue;
2909 resume_info[n].sig = 0;
2910 n++;
2911 }
2912
2913 resume (resume_info, n);
2914 }
2915
2916 /* Callback for for_each_inferior. Make a new stop reply for each
2917 stopped thread. */
2918
2919 static int
2920 queue_stop_reply_callback (struct inferior_list_entry *entry, void *arg)
2921 {
2922 struct thread_info *thread = (struct thread_info *) entry;
2923
2924 /* For now, assume targets that don't have this callback also don't
2925 manage the thread's last_status field. */
2926 if (the_target->thread_stopped == NULL)
2927 {
2928 struct vstop_notif *new_notif = XNEW (struct vstop_notif);
2929
2930 new_notif->ptid = entry->id;
2931 new_notif->status = thread->last_status;
2932 /* Pass the last stop reply back to GDB, but don't notify
2933 yet. */
2934 notif_event_enque (&notif_stop,
2935 (struct notif_event *) new_notif);
2936 }
2937 else
2938 {
2939 if (thread_stopped (thread))
2940 {
2941 if (debug_threads)
2942 {
2943 char *status_string
2944 = target_waitstatus_to_string (&thread->last_status);
2945
2946 debug_printf ("Reporting thread %s as already stopped with %s\n",
2947 target_pid_to_str (entry->id),
2948 status_string);
2949
2950 xfree (status_string);
2951 }
2952
2953 gdb_assert (thread->last_status.kind != TARGET_WAITKIND_IGNORE);
2954
2955 /* Pass the last stop reply back to GDB, but don't notify
2956 yet. */
2957 queue_stop_reply (entry->id, &thread->last_status);
2958 }
2959 }
2960
2961 return 0;
2962 }
2963
2964 /* Set this inferior threads's state as "want-stopped". We won't
2965 resume this thread until the client gives us another action for
2966 it. */
2967
2968 static void
2969 gdb_wants_thread_stopped (struct inferior_list_entry *entry)
2970 {
2971 struct thread_info *thread = (struct thread_info *) entry;
2972
2973 thread->last_resume_kind = resume_stop;
2974
2975 if (thread->last_status.kind == TARGET_WAITKIND_IGNORE)
2976 {
2977 /* Most threads are stopped implicitly (all-stop); tag that with
2978 signal 0. */
2979 thread->last_status.kind = TARGET_WAITKIND_STOPPED;
2980 thread->last_status.value.sig = GDB_SIGNAL_0;
2981 }
2982 }
2983
2984 /* Set all threads' states as "want-stopped". */
2985
2986 static void
2987 gdb_wants_all_threads_stopped (void)
2988 {
2989 for_each_inferior (&all_threads, gdb_wants_thread_stopped);
2990 }
2991
2992 /* Clear the gdb_detached flag of every process. */
2993
2994 static void
2995 gdb_reattached_process (struct inferior_list_entry *entry)
2996 {
2997 struct process_info *process = (struct process_info *) entry;
2998
2999 process->gdb_detached = 0;
3000 }
3001
3002 /* Callback for for_each_inferior. Clear the thread's pending status
3003 flag. */
3004
3005 static void
3006 clear_pending_status_callback (struct inferior_list_entry *entry)
3007 {
3008 struct thread_info *thread = (struct thread_info *) entry;
3009
3010 thread->status_pending_p = 0;
3011 }
3012
3013 /* Callback for for_each_inferior. If the thread is stopped with an
3014 interesting event, mark it as having a pending event. */
3015
3016 static void
3017 set_pending_status_callback (struct inferior_list_entry *entry)
3018 {
3019 struct thread_info *thread = (struct thread_info *) entry;
3020
3021 if (thread->last_status.kind != TARGET_WAITKIND_STOPPED
3022 || (thread->last_status.value.sig != GDB_SIGNAL_0
3023 /* A breakpoint, watchpoint or finished step from a previous
3024 GDB run isn't considered interesting for a new GDB run.
3025 If we left those pending, the new GDB could consider them
3026 random SIGTRAPs. This leaves out real async traps. We'd
3027 have to peek into the (target-specific) siginfo to
3028 distinguish those. */
3029 && thread->last_status.value.sig != GDB_SIGNAL_TRAP))
3030 thread->status_pending_p = 1;
3031 }
3032
3033 /* Callback for find_inferior. Return true if ENTRY (a thread) has a
3034 pending status to report to GDB. */
3035
3036 static int
3037 find_status_pending_thread_callback (struct inferior_list_entry *entry, void *data)
3038 {
3039 struct thread_info *thread = (struct thread_info *) entry;
3040
3041 return thread->status_pending_p;
3042 }
3043
3044 /* Status handler for the '?' packet. */
3045
3046 static void
3047 handle_status (char *own_buf)
3048 {
3049 /* GDB is connected, don't forward events to the target anymore. */
3050 for_each_inferior (&all_processes, gdb_reattached_process);
3051
3052 /* In non-stop mode, we must send a stop reply for each stopped
3053 thread. In all-stop mode, just send one for the first stopped
3054 thread we find. */
3055
3056 if (non_stop)
3057 {
3058 find_inferior (&all_threads, queue_stop_reply_callback, NULL);
3059
3060 /* The first is sent immediatly. OK is sent if there is no
3061 stopped thread, which is the same handling of the vStopped
3062 packet (by design). */
3063 notif_write_event (&notif_stop, own_buf);
3064 }
3065 else
3066 {
3067 struct inferior_list_entry *thread = NULL;
3068
3069 pause_all (0);
3070 stabilize_threads ();
3071 gdb_wants_all_threads_stopped ();
3072
3073 /* We can only report one status, but we might be coming out of
3074 non-stop -- if more than one thread is stopped with
3075 interesting events, leave events for the threads we're not
3076 reporting now pending. They'll be reported the next time the
3077 threads are resumed. Start by marking all interesting events
3078 as pending. */
3079 for_each_inferior (&all_threads, set_pending_status_callback);
3080
3081 /* Prefer the last thread that reported an event to GDB (even if
3082 that was a GDB_SIGNAL_TRAP). */
3083 if (last_status.kind != TARGET_WAITKIND_IGNORE
3084 && last_status.kind != TARGET_WAITKIND_EXITED
3085 && last_status.kind != TARGET_WAITKIND_SIGNALLED)
3086 thread = find_inferior_id (&all_threads, last_ptid);
3087
3088 /* If the last event thread is not found for some reason, look
3089 for some other thread that might have an event to report. */
3090 if (thread == NULL)
3091 thread = find_inferior (&all_threads,
3092 find_status_pending_thread_callback, NULL);
3093
3094 /* If we're still out of luck, simply pick the first thread in
3095 the thread list. */
3096 if (thread == NULL)
3097 thread = get_first_inferior (&all_threads);
3098
3099 if (thread != NULL)
3100 {
3101 struct thread_info *tp = (struct thread_info *) thread;
3102
3103 /* We're reporting this event, so it's no longer
3104 pending. */
3105 tp->status_pending_p = 0;
3106
3107 /* GDB assumes the current thread is the thread we're
3108 reporting the status for. */
3109 general_thread = thread->id;
3110 set_desired_thread (1);
3111
3112 gdb_assert (tp->last_status.kind != TARGET_WAITKIND_IGNORE);
3113 prepare_resume_reply (own_buf, tp->entry.id, &tp->last_status);
3114 }
3115 else
3116 strcpy (own_buf, "W00");
3117 }
3118 }
3119
3120 static void
3121 gdbserver_version (void)
3122 {
3123 printf ("GNU gdbserver %s%s\n"
3124 "Copyright (C) 2015 Free Software Foundation, Inc.\n"
3125 "gdbserver is free software, covered by the "
3126 "GNU General Public License.\n"
3127 "This gdbserver was configured as \"%s\"\n",
3128 PKGVERSION, version, host_name);
3129 }
3130
3131 static void
3132 gdbserver_usage (FILE *stream)
3133 {
3134 fprintf (stream, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3135 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3136 "\tgdbserver [OPTIONS] --multi COMM\n"
3137 "\n"
3138 "COMM may either be a tty device (for serial debugging),\n"
3139 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3140 "stdin/stdout of gdbserver.\n"
3141 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3142 "PID is the process ID to attach to, when --attach is specified.\n"
3143 "\n"
3144 "Operating modes:\n"
3145 "\n"
3146 " --attach Attach to running process PID.\n"
3147 " --multi Start server without a specific program, and\n"
3148 " only quit when explicitly commanded.\n"
3149 " --once Exit after the first connection has closed.\n"
3150 " --help Print this message and then exit.\n"
3151 " --version Display version information and exit.\n"
3152 "\n"
3153 "Other options:\n"
3154 "\n"
3155 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3156 " --disable-randomization\n"
3157 " Run PROG with address space randomization disabled.\n"
3158 " --no-disable-randomization\n"
3159 " Don't disable address space randomization when\n"
3160 " starting PROG.\n"
3161 "\n"
3162 "Debug options:\n"
3163 "\n"
3164 " --debug Enable general debugging output.\n"
3165 " --debug-format=opt1[,opt2,...]\n"
3166 " Specify extra content in debugging output.\n"
3167 " Options:\n"
3168 " all\n"
3169 " none\n"
3170 " timestamp\n"
3171 " --remote-debug Enable remote protocol debugging output.\n"
3172 " --disable-packet=opt1[,opt2,...]\n"
3173 " Disable support for RSP packets or features.\n"
3174 " Options:\n"
3175 " vCont, Tthread, qC, qfThreadInfo and \n"
3176 " threads (disable all threading packets).\n"
3177 "\n"
3178 "For more information, consult the GDB manual (available as on-line \n"
3179 "info or a printed manual).\n");
3180 if (REPORT_BUGS_TO[0] && stream == stdout)
3181 fprintf (stream, "Report bugs to \"%s\".\n", REPORT_BUGS_TO);
3182 }
3183
3184 static void
3185 gdbserver_show_disableable (FILE *stream)
3186 {
3187 fprintf (stream, "Disableable packets:\n"
3188 " vCont \tAll vCont packets\n"
3189 " qC \tQuerying the current thread\n"
3190 " qfThreadInfo\tThread listing\n"
3191 " Tthread \tPassing the thread specifier in the "
3192 "T stop reply packet\n"
3193 " threads \tAll of the above\n");
3194 }
3195
3196
3197 #undef require_running
3198 #define require_running(BUF) \
3199 if (!target_running ()) \
3200 { \
3201 write_enn (BUF); \
3202 break; \
3203 }
3204
3205 static int
3206 first_thread_of (struct inferior_list_entry *entry, void *args)
3207 {
3208 int pid = * (int *) args;
3209
3210 if (ptid_get_pid (entry->id) == pid)
3211 return 1;
3212
3213 return 0;
3214 }
3215
3216 static void
3217 kill_inferior_callback (struct inferior_list_entry *entry)
3218 {
3219 struct process_info *process = (struct process_info *) entry;
3220 int pid = ptid_get_pid (process->entry.id);
3221
3222 kill_inferior (pid);
3223 discard_queued_stop_replies (pid_to_ptid (pid));
3224 }
3225
3226 /* Callback for for_each_inferior to detach or kill the inferior,
3227 depending on whether we attached to it or not.
3228 We inform the user whether we're detaching or killing the process
3229 as this is only called when gdbserver is about to exit. */
3230
3231 static void
3232 detach_or_kill_inferior_callback (struct inferior_list_entry *entry)
3233 {
3234 struct process_info *process = (struct process_info *) entry;
3235 int pid = ptid_get_pid (process->entry.id);
3236
3237 if (process->attached)
3238 detach_inferior (pid);
3239 else
3240 kill_inferior (pid);
3241
3242 discard_queued_stop_replies (pid_to_ptid (pid));
3243 }
3244
3245 /* for_each_inferior callback for detach_or_kill_for_exit to print
3246 the pids of started inferiors. */
3247
3248 static void
3249 print_started_pid (struct inferior_list_entry *entry)
3250 {
3251 struct process_info *process = (struct process_info *) entry;
3252
3253 if (! process->attached)
3254 {
3255 int pid = ptid_get_pid (process->entry.id);
3256 fprintf (stderr, " %d", pid);
3257 }
3258 }
3259
3260 /* for_each_inferior callback for detach_or_kill_for_exit to print
3261 the pids of attached inferiors. */
3262
3263 static void
3264 print_attached_pid (struct inferior_list_entry *entry)
3265 {
3266 struct process_info *process = (struct process_info *) entry;
3267
3268 if (process->attached)
3269 {
3270 int pid = ptid_get_pid (process->entry.id);
3271 fprintf (stderr, " %d", pid);
3272 }
3273 }
3274
3275 /* Call this when exiting gdbserver with possible inferiors that need
3276 to be killed or detached from. */
3277
3278 static void
3279 detach_or_kill_for_exit (void)
3280 {
3281 /* First print a list of the inferiors we will be killing/detaching.
3282 This is to assist the user, for example, in case the inferior unexpectedly
3283 dies after we exit: did we screw up or did the inferior exit on its own?
3284 Having this info will save some head-scratching. */
3285
3286 if (have_started_inferiors_p ())
3287 {
3288 fprintf (stderr, "Killing process(es):");
3289 for_each_inferior (&all_processes, print_started_pid);
3290 fprintf (stderr, "\n");
3291 }
3292 if (have_attached_inferiors_p ())
3293 {
3294 fprintf (stderr, "Detaching process(es):");
3295 for_each_inferior (&all_processes, print_attached_pid);
3296 fprintf (stderr, "\n");
3297 }
3298
3299 /* Now we can kill or detach the inferiors. */
3300
3301 for_each_inferior (&all_processes, detach_or_kill_inferior_callback);
3302 }
3303
3304 /* Value that will be passed to exit(3) when gdbserver exits. */
3305 static int exit_code;
3306
3307 /* Cleanup version of detach_or_kill_for_exit. */
3308
3309 static void
3310 detach_or_kill_for_exit_cleanup (void *ignore)
3311 {
3312
3313 TRY
3314 {
3315 detach_or_kill_for_exit ();
3316 }
3317
3318 CATCH (exception, RETURN_MASK_ALL)
3319 {
3320 fflush (stdout);
3321 fprintf (stderr, "Detach or kill failed: %s\n", exception.message);
3322 exit_code = 1;
3323 }
3324 END_CATCH
3325 }
3326
3327 /* Main function. This is called by the real "main" function,
3328 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
3329
3330 static void ATTRIBUTE_NORETURN
3331 captured_main (int argc, char *argv[])
3332 {
3333 int bad_attach;
3334 int pid;
3335 char *arg_end, *port;
3336 char **next_arg = &argv[1];
3337 volatile int multi_mode = 0;
3338 volatile int attach = 0;
3339 int was_running;
3340
3341 while (*next_arg != NULL && **next_arg == '-')
3342 {
3343 if (strcmp (*next_arg, "--version") == 0)
3344 {
3345 gdbserver_version ();
3346 exit (0);
3347 }
3348 else if (strcmp (*next_arg, "--help") == 0)
3349 {
3350 gdbserver_usage (stdout);
3351 exit (0);
3352 }
3353 else if (strcmp (*next_arg, "--attach") == 0)
3354 attach = 1;
3355 else if (strcmp (*next_arg, "--multi") == 0)
3356 multi_mode = 1;
3357 else if (strcmp (*next_arg, "--wrapper") == 0)
3358 {
3359 next_arg++;
3360
3361 wrapper_argv = next_arg;
3362 while (*next_arg != NULL && strcmp (*next_arg, "--") != 0)
3363 next_arg++;
3364
3365 if (next_arg == wrapper_argv || *next_arg == NULL)
3366 {
3367 gdbserver_usage (stderr);
3368 exit (1);
3369 }
3370
3371 /* Consume the "--". */
3372 *next_arg = NULL;
3373 }
3374 else if (strcmp (*next_arg, "--debug") == 0)
3375 debug_threads = 1;
3376 else if (startswith (*next_arg, "--debug-format="))
3377 {
3378 char *error_msg
3379 = parse_debug_format_options ((*next_arg)
3380 + sizeof ("--debug-format=") - 1, 0);
3381
3382 if (error_msg != NULL)
3383 {
3384 fprintf (stderr, "%s", error_msg);
3385 exit (1);
3386 }
3387 }
3388 else if (strcmp (*next_arg, "--remote-debug") == 0)
3389 remote_debug = 1;
3390 else if (strcmp (*next_arg, "--disable-packet") == 0)
3391 {
3392 gdbserver_show_disableable (stdout);
3393 exit (0);
3394 }
3395 else if (startswith (*next_arg, "--disable-packet="))
3396 {
3397 char *packets, *tok;
3398
3399 packets = *next_arg += sizeof ("--disable-packet=") - 1;
3400 for (tok = strtok (packets, ",");
3401 tok != NULL;
3402 tok = strtok (NULL, ","))
3403 {
3404 if (strcmp ("vCont", tok) == 0)
3405 disable_packet_vCont = 1;
3406 else if (strcmp ("Tthread", tok) == 0)
3407 disable_packet_Tthread = 1;
3408 else if (strcmp ("qC", tok) == 0)
3409 disable_packet_qC = 1;
3410 else if (strcmp ("qfThreadInfo", tok) == 0)
3411 disable_packet_qfThreadInfo = 1;
3412 else if (strcmp ("threads", tok) == 0)
3413 {
3414 disable_packet_vCont = 1;
3415 disable_packet_Tthread = 1;
3416 disable_packet_qC = 1;
3417 disable_packet_qfThreadInfo = 1;
3418 }
3419 else
3420 {
3421 fprintf (stderr, "Don't know how to disable \"%s\".\n\n",
3422 tok);
3423 gdbserver_show_disableable (stderr);
3424 exit (1);
3425 }
3426 }
3427 }
3428 else if (strcmp (*next_arg, "-") == 0)
3429 {
3430 /* "-" specifies a stdio connection and is a form of port
3431 specification. */
3432 *next_arg = STDIO_CONNECTION_NAME;
3433 break;
3434 }
3435 else if (strcmp (*next_arg, "--disable-randomization") == 0)
3436 disable_randomization = 1;
3437 else if (strcmp (*next_arg, "--no-disable-randomization") == 0)
3438 disable_randomization = 0;
3439 else if (strcmp (*next_arg, "--once") == 0)
3440 run_once = 1;
3441 else
3442 {
3443 fprintf (stderr, "Unknown argument: %s\n", *next_arg);
3444 exit (1);
3445 }
3446
3447 next_arg++;
3448 continue;
3449 }
3450
3451 port = *next_arg;
3452 next_arg++;
3453 if (port == NULL || (!attach && !multi_mode && *next_arg == NULL))
3454 {
3455 gdbserver_usage (stderr);
3456 exit (1);
3457 }
3458
3459 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
3460 opened by remote_prepare. */
3461 notice_open_fds ();
3462
3463 /* We need to know whether the remote connection is stdio before
3464 starting the inferior. Inferiors created in this scenario have
3465 stdin,stdout redirected. So do this here before we call
3466 start_inferior. */
3467 remote_prepare (port);
3468
3469 bad_attach = 0;
3470 pid = 0;
3471
3472 /* --attach used to come after PORT, so allow it there for
3473 compatibility. */
3474 if (*next_arg != NULL && strcmp (*next_arg, "--attach") == 0)
3475 {
3476 attach = 1;
3477 next_arg++;
3478 }
3479
3480 if (attach
3481 && (*next_arg == NULL
3482 || (*next_arg)[0] == '\0'
3483 || (pid = strtoul (*next_arg, &arg_end, 0)) == 0
3484 || *arg_end != '\0'
3485 || next_arg[1] != NULL))
3486 bad_attach = 1;
3487
3488 if (bad_attach)
3489 {
3490 gdbserver_usage (stderr);
3491 exit (1);
3492 }
3493
3494 initialize_async_io ();
3495 initialize_low ();
3496 initialize_event_loop ();
3497 if (target_supports_tracepoints ())
3498 initialize_tracepoint ();
3499 initialize_notif ();
3500
3501 own_buf = xmalloc (PBUFSIZ + 1);
3502 mem_buf = xmalloc (PBUFSIZ);
3503
3504 if (pid == 0 && *next_arg != NULL)
3505 {
3506 int i, n;
3507
3508 n = argc - (next_arg - argv);
3509 program_argv = xmalloc (sizeof (char *) * (n + 1));
3510 for (i = 0; i < n; i++)
3511 program_argv[i] = xstrdup (next_arg[i]);
3512 program_argv[i] = NULL;
3513
3514 /* Wait till we are at first instruction in program. */
3515 start_inferior (program_argv);
3516
3517 /* We are now (hopefully) stopped at the first instruction of
3518 the target process. This assumes that the target process was
3519 successfully created. */
3520 }
3521 else if (pid != 0)
3522 {
3523 if (attach_inferior (pid) == -1)
3524 error ("Attaching not supported on this target");
3525
3526 /* Otherwise succeeded. */
3527 }
3528 else
3529 {
3530 last_status.kind = TARGET_WAITKIND_EXITED;
3531 last_status.value.integer = 0;
3532 last_ptid = minus_one_ptid;
3533 }
3534 make_cleanup (detach_or_kill_for_exit_cleanup, NULL);
3535
3536 /* Don't report shared library events on the initial connection,
3537 even if some libraries are preloaded. Avoids the "stopped by
3538 shared library event" notice on gdb side. */
3539 dlls_changed = 0;
3540
3541 if (last_status.kind == TARGET_WAITKIND_EXITED
3542 || last_status.kind == TARGET_WAITKIND_SIGNALLED)
3543 was_running = 0;
3544 else
3545 was_running = 1;
3546
3547 if (!was_running && !multi_mode)
3548 error ("No program to debug");
3549
3550 while (1)
3551 {
3552
3553 noack_mode = 0;
3554 multi_process = 0;
3555 report_fork_events = 0;
3556 report_vfork_events = 0;
3557 report_exec_events = 0;
3558 /* Be sure we're out of tfind mode. */
3559 current_traceframe = -1;
3560 cont_thread = null_ptid;
3561 swbreak_feature = 0;
3562 hwbreak_feature = 0;
3563
3564 remote_open (port);
3565
3566 TRY
3567 {
3568 /* Wait for events. This will return when all event sources
3569 are removed from the event loop. */
3570 start_event_loop ();
3571
3572 /* If an exit was requested (using the "monitor exit"
3573 command), terminate now. The only other way to get
3574 here is for getpkt to fail; close the connection
3575 and reopen it at the top of the loop. */
3576
3577 if (exit_requested || run_once)
3578 throw_quit ("Quit");
3579
3580 fprintf (stderr,
3581 "Remote side has terminated connection. "
3582 "GDBserver will reopen the connection.\n");
3583
3584 /* Get rid of any pending statuses. An eventual reconnection
3585 (by the same GDB instance or another) will refresh all its
3586 state from scratch. */
3587 discard_queued_stop_replies (minus_one_ptid);
3588 for_each_inferior (&all_threads,
3589 clear_pending_status_callback);
3590
3591 if (tracing)
3592 {
3593 if (disconnected_tracing)
3594 {
3595 /* Try to enable non-stop/async mode, so we we can
3596 both wait for an async socket accept, and handle
3597 async target events simultaneously. There's also
3598 no point either in having the target always stop
3599 all threads, when we're going to pass signals
3600 down without informing GDB. */
3601 if (!non_stop)
3602 {
3603 if (start_non_stop (1))
3604 non_stop = 1;
3605
3606 /* Detaching implicitly resumes all threads;
3607 simply disconnecting does not. */
3608 }
3609 }
3610 else
3611 {
3612 fprintf (stderr,
3613 "Disconnected tracing disabled; "
3614 "stopping trace run.\n");
3615 stop_tracing ();
3616 }
3617 }
3618 }
3619 CATCH (exception, RETURN_MASK_ERROR)
3620 {
3621 fflush (stdout);
3622 fprintf (stderr, "gdbserver: %s\n", exception.message);
3623
3624 if (response_needed)
3625 {
3626 write_enn (own_buf);
3627 putpkt (own_buf);
3628 }
3629
3630 if (run_once)
3631 throw_quit ("Quit");
3632 }
3633 END_CATCH
3634 }
3635 }
3636
3637 /* Main function. */
3638
3639 int
3640 main (int argc, char *argv[])
3641 {
3642
3643 TRY
3644 {
3645 captured_main (argc, argv);
3646 }
3647 CATCH (exception, RETURN_MASK_ALL)
3648 {
3649 if (exception.reason == RETURN_ERROR)
3650 {
3651 fflush (stdout);
3652 fprintf (stderr, "%s\n", exception.message);
3653 fprintf (stderr, "Exiting\n");
3654 exit_code = 1;
3655 }
3656
3657 exit (exit_code);
3658 }
3659 END_CATCH
3660
3661 gdb_assert_not_reached ("captured_main should never return");
3662 }
3663
3664 /* Skip PACKET until the next semi-colon (or end of string). */
3665
3666 static void
3667 skip_to_semicolon (char **packet)
3668 {
3669 while (**packet != '\0' && **packet != ';')
3670 (*packet)++;
3671 }
3672
3673 /* Process options coming from Z packets for a breakpoint. PACKET is
3674 the packet buffer. *PACKET is updated to point to the first char
3675 after the last processed option. */
3676
3677 static void
3678 process_point_options (struct breakpoint *bp, char **packet)
3679 {
3680 char *dataptr = *packet;
3681 int persist;
3682
3683 /* Check if data has the correct format. */
3684 if (*dataptr != ';')
3685 return;
3686
3687 dataptr++;
3688
3689 while (*dataptr)
3690 {
3691 if (*dataptr == ';')
3692 ++dataptr;
3693
3694 if (*dataptr == 'X')
3695 {
3696 /* Conditional expression. */
3697 if (debug_threads)
3698 debug_printf ("Found breakpoint condition.\n");
3699 if (!add_breakpoint_condition (bp, &dataptr))
3700 skip_to_semicolon (&dataptr);
3701 }
3702 else if (startswith (dataptr, "cmds:"))
3703 {
3704 dataptr += strlen ("cmds:");
3705 if (debug_threads)
3706 debug_printf ("Found breakpoint commands %s.\n", dataptr);
3707 persist = (*dataptr == '1');
3708 dataptr += 2;
3709 if (add_breakpoint_commands (bp, &dataptr, persist))
3710 skip_to_semicolon (&dataptr);
3711 }
3712 else
3713 {
3714 fprintf (stderr, "Unknown token %c, ignoring.\n",
3715 *dataptr);
3716 /* Skip tokens until we find one that we recognize. */
3717 skip_to_semicolon (&dataptr);
3718 }
3719 }
3720 *packet = dataptr;
3721 }
3722
3723 /* Event loop callback that handles a serial event. The first byte in
3724 the serial buffer gets us here. We expect characters to arrive at
3725 a brisk pace, so we read the rest of the packet with a blocking
3726 getpkt call. */
3727
3728 static int
3729 process_serial_event (void)
3730 {
3731 char ch;
3732 int i = 0;
3733 int signal;
3734 unsigned int len;
3735 int res;
3736 CORE_ADDR mem_addr;
3737 int pid;
3738 unsigned char sig;
3739 int packet_len;
3740 int new_packet_len = -1;
3741
3742 /* Used to decide when gdbserver should exit in
3743 multi-mode/remote. */
3744 static int have_ran = 0;
3745
3746 if (!have_ran)
3747 have_ran = target_running ();
3748
3749 disable_async_io ();
3750
3751 response_needed = 0;
3752 packet_len = getpkt (own_buf);
3753 if (packet_len <= 0)
3754 {
3755 remote_close ();
3756 /* Force an event loop break. */
3757 return -1;
3758 }
3759 response_needed = 1;
3760
3761 i = 0;
3762 ch = own_buf[i++];
3763 switch (ch)
3764 {
3765 case 'q':
3766 handle_query (own_buf, packet_len, &new_packet_len);
3767 break;
3768 case 'Q':
3769 handle_general_set (own_buf);
3770 break;
3771 case 'D':
3772 require_running (own_buf);
3773
3774 if (multi_process)
3775 {
3776 i++; /* skip ';' */
3777 pid = strtol (&own_buf[i], NULL, 16);
3778 }
3779 else
3780 pid = ptid_get_pid (current_ptid);
3781
3782 if ((tracing && disconnected_tracing) || any_persistent_commands ())
3783 {
3784 struct thread_resume resume_info;
3785 struct process_info *process = find_process_pid (pid);
3786
3787 if (process == NULL)
3788 {
3789 write_enn (own_buf);
3790 break;
3791 }
3792
3793 if (tracing && disconnected_tracing)
3794 fprintf (stderr,
3795 "Disconnected tracing in effect, "
3796 "leaving gdbserver attached to the process\n");
3797
3798 if (any_persistent_commands ())
3799 fprintf (stderr,
3800 "Persistent commands are present, "
3801 "leaving gdbserver attached to the process\n");
3802
3803 /* Make sure we're in non-stop/async mode, so we we can both
3804 wait for an async socket accept, and handle async target
3805 events simultaneously. There's also no point either in
3806 having the target stop all threads, when we're going to
3807 pass signals down without informing GDB. */
3808 if (!non_stop)
3809 {
3810 if (debug_threads)
3811 debug_printf ("Forcing non-stop mode\n");
3812
3813 non_stop = 1;
3814 start_non_stop (1);
3815 }
3816
3817 process->gdb_detached = 1;
3818
3819 /* Detaching implicitly resumes all threads. */
3820 resume_info.thread = minus_one_ptid;
3821 resume_info.kind = resume_continue;
3822 resume_info.sig = 0;
3823 (*the_target->resume) (&resume_info, 1);
3824
3825 write_ok (own_buf);
3826 break; /* from switch/case */
3827 }
3828
3829 fprintf (stderr, "Detaching from process %d\n", pid);
3830 stop_tracing ();
3831 if (detach_inferior (pid) != 0)
3832 write_enn (own_buf);
3833 else
3834 {
3835 discard_queued_stop_replies (pid_to_ptid (pid));
3836 write_ok (own_buf);
3837
3838 if (extended_protocol)
3839 {
3840 /* Treat this like a normal program exit. */
3841 last_status.kind = TARGET_WAITKIND_EXITED;
3842 last_status.value.integer = 0;
3843 last_ptid = pid_to_ptid (pid);
3844
3845 current_thread = NULL;
3846 }
3847 else
3848 {
3849 putpkt (own_buf);
3850 remote_close ();
3851
3852 /* If we are attached, then we can exit. Otherwise, we
3853 need to hang around doing nothing, until the child is
3854 gone. */
3855 join_inferior (pid);
3856 exit (0);
3857 }
3858 }
3859 break;
3860 case '!':
3861 extended_protocol = 1;
3862 write_ok (own_buf);
3863 break;
3864 case '?':
3865 handle_status (own_buf);
3866 break;
3867 case 'H':
3868 if (own_buf[1] == 'c' || own_buf[1] == 'g' || own_buf[1] == 's')
3869 {
3870 ptid_t gdb_id, thread_id;
3871 int pid;
3872
3873 require_running (own_buf);
3874
3875 gdb_id = read_ptid (&own_buf[2], NULL);
3876
3877 pid = ptid_get_pid (gdb_id);
3878
3879 if (ptid_equal (gdb_id, null_ptid)
3880 || ptid_equal (gdb_id, minus_one_ptid))
3881 thread_id = null_ptid;
3882 else if (pid != 0
3883 && ptid_equal (pid_to_ptid (pid),
3884 gdb_id))
3885 {
3886 struct thread_info *thread =
3887 (struct thread_info *) find_inferior (&all_threads,
3888 first_thread_of,
3889 &pid);
3890 if (!thread)
3891 {
3892 write_enn (own_buf);
3893 break;
3894 }
3895
3896 thread_id = thread->entry.id;
3897 }
3898 else
3899 {
3900 thread_id = gdb_id_to_thread_id (gdb_id);
3901 if (ptid_equal (thread_id, null_ptid))
3902 {
3903 write_enn (own_buf);
3904 break;
3905 }
3906 }
3907
3908 if (own_buf[1] == 'g')
3909 {
3910 if (ptid_equal (thread_id, null_ptid))
3911 {
3912 /* GDB is telling us to choose any thread. Check if
3913 the currently selected thread is still valid. If
3914 it is not, select the first available. */
3915 struct thread_info *thread =
3916 (struct thread_info *) find_inferior_id (&all_threads,
3917 general_thread);
3918 if (thread == NULL)
3919 thread = get_first_thread ();
3920 thread_id = thread->entry.id;
3921 }
3922
3923 general_thread = thread_id;
3924 set_desired_thread (1);
3925 gdb_assert (current_thread != NULL);
3926 }
3927 else if (own_buf[1] == 'c')
3928 cont_thread = thread_id;
3929
3930 write_ok (own_buf);
3931 }
3932 else
3933 {
3934 /* Silently ignore it so that gdb can extend the protocol
3935 without compatibility headaches. */
3936 own_buf[0] = '\0';
3937 }
3938 break;
3939 case 'g':
3940 require_running (own_buf);
3941 if (current_traceframe >= 0)
3942 {
3943 struct regcache *regcache
3944 = new_register_cache (current_target_desc ());
3945
3946 if (fetch_traceframe_registers (current_traceframe,
3947 regcache, -1) == 0)
3948 registers_to_string (regcache, own_buf);
3949 else
3950 write_enn (own_buf);
3951 free_register_cache (regcache);
3952 }
3953 else
3954 {
3955 struct regcache *regcache;
3956
3957 if (!set_desired_thread (1))
3958 write_enn (own_buf);
3959 else
3960 {
3961 regcache = get_thread_regcache (current_thread, 1);
3962 registers_to_string (regcache, own_buf);
3963 }
3964 }
3965 break;
3966 case 'G':
3967 require_running (own_buf);
3968 if (current_traceframe >= 0)
3969 write_enn (own_buf);
3970 else
3971 {
3972 struct regcache *regcache;
3973
3974 if (!set_desired_thread (1))
3975 write_enn (own_buf);
3976 else
3977 {
3978 regcache = get_thread_regcache (current_thread, 1);
3979 registers_from_string (regcache, &own_buf[1]);
3980 write_ok (own_buf);
3981 }
3982 }
3983 break;
3984 case 'm':
3985 require_running (own_buf);
3986 decode_m_packet (&own_buf[1], &mem_addr, &len);
3987 res = gdb_read_memory (mem_addr, mem_buf, len);
3988 if (res < 0)
3989 write_enn (own_buf);
3990 else
3991 bin2hex (mem_buf, own_buf, res);
3992 break;
3993 case 'M':
3994 require_running (own_buf);
3995 decode_M_packet (&own_buf[1], &mem_addr, &len, &mem_buf);
3996 if (gdb_write_memory (mem_addr, mem_buf, len) == 0)
3997 write_ok (own_buf);
3998 else
3999 write_enn (own_buf);
4000 break;
4001 case 'X':
4002 require_running (own_buf);
4003 if (decode_X_packet (&own_buf[1], packet_len - 1,
4004 &mem_addr, &len, &mem_buf) < 0
4005 || gdb_write_memory (mem_addr, mem_buf, len) != 0)
4006 write_enn (own_buf);
4007 else
4008 write_ok (own_buf);
4009 break;
4010 case 'C':
4011 require_running (own_buf);
4012 hex2bin (own_buf + 1, &sig, 1);
4013 if (gdb_signal_to_host_p (sig))
4014 signal = gdb_signal_to_host (sig);
4015 else
4016 signal = 0;
4017 myresume (own_buf, 0, signal);
4018 break;
4019 case 'S':
4020 require_running (own_buf);
4021 hex2bin (own_buf + 1, &sig, 1);
4022 if (gdb_signal_to_host_p (sig))
4023 signal = gdb_signal_to_host (sig);
4024 else
4025 signal = 0;
4026 myresume (own_buf, 1, signal);
4027 break;
4028 case 'c':
4029 require_running (own_buf);
4030 signal = 0;
4031 myresume (own_buf, 0, signal);
4032 break;
4033 case 's':
4034 require_running (own_buf);
4035 signal = 0;
4036 myresume (own_buf, 1, signal);
4037 break;
4038 case 'Z': /* insert_ ... */
4039 /* Fallthrough. */
4040 case 'z': /* remove_ ... */
4041 {
4042 char *dataptr;
4043 ULONGEST addr;
4044 int len;
4045 char type = own_buf[1];
4046 int res;
4047 const int insert = ch == 'Z';
4048 char *p = &own_buf[3];
4049
4050 p = unpack_varlen_hex (p, &addr);
4051 len = strtol (p + 1, &dataptr, 16);
4052
4053 if (insert)
4054 {
4055 struct breakpoint *bp;
4056
4057 bp = set_gdb_breakpoint (type, addr, len, &res);
4058 if (bp != NULL)
4059 {
4060 res = 0;
4061
4062 /* GDB may have sent us a list of *point parameters to
4063 be evaluated on the target's side. Read such list
4064 here. If we already have a list of parameters, GDB
4065 is telling us to drop that list and use this one
4066 instead. */
4067 clear_breakpoint_conditions_and_commands (bp);
4068 process_point_options (bp, &dataptr);
4069 }
4070 }
4071 else
4072 res = delete_gdb_breakpoint (type, addr, len);
4073
4074 if (res == 0)
4075 write_ok (own_buf);
4076 else if (res == 1)
4077 /* Unsupported. */
4078 own_buf[0] = '\0';
4079 else
4080 write_enn (own_buf);
4081 break;
4082 }
4083 case 'k':
4084 response_needed = 0;
4085 if (!target_running ())
4086 /* The packet we received doesn't make sense - but we can't
4087 reply to it, either. */
4088 return 0;
4089
4090 fprintf (stderr, "Killing all inferiors\n");
4091 for_each_inferior (&all_processes, kill_inferior_callback);
4092
4093 /* When using the extended protocol, we wait with no program
4094 running. The traditional protocol will exit instead. */
4095 if (extended_protocol)
4096 {
4097 last_status.kind = TARGET_WAITKIND_EXITED;
4098 last_status.value.sig = GDB_SIGNAL_KILL;
4099 return 0;
4100 }
4101 else
4102 exit (0);
4103
4104 case 'T':
4105 {
4106 ptid_t gdb_id, thread_id;
4107
4108 require_running (own_buf);
4109
4110 gdb_id = read_ptid (&own_buf[1], NULL);
4111 thread_id = gdb_id_to_thread_id (gdb_id);
4112 if (ptid_equal (thread_id, null_ptid))
4113 {
4114 write_enn (own_buf);
4115 break;
4116 }
4117
4118 if (mythread_alive (thread_id))
4119 write_ok (own_buf);
4120 else
4121 write_enn (own_buf);
4122 }
4123 break;
4124 case 'R':
4125 response_needed = 0;
4126
4127 /* Restarting the inferior is only supported in the extended
4128 protocol. */
4129 if (extended_protocol)
4130 {
4131 if (target_running ())
4132 for_each_inferior (&all_processes,
4133 kill_inferior_callback);
4134 fprintf (stderr, "GDBserver restarting\n");
4135
4136 /* Wait till we are at 1st instruction in prog. */
4137 if (program_argv != NULL)
4138 {
4139 start_inferior (program_argv);
4140 if (last_status.kind == TARGET_WAITKIND_STOPPED)
4141 {
4142 /* Stopped at the first instruction of the target
4143 process. */
4144 general_thread = last_ptid;
4145 }
4146 else
4147 {
4148 /* Something went wrong. */
4149 general_thread = null_ptid;
4150 }
4151 }
4152 else
4153 {
4154 last_status.kind = TARGET_WAITKIND_EXITED;
4155 last_status.value.sig = GDB_SIGNAL_KILL;
4156 }
4157 return 0;
4158 }
4159 else
4160 {
4161 /* It is a request we don't understand. Respond with an
4162 empty packet so that gdb knows that we don't support this
4163 request. */
4164 own_buf[0] = '\0';
4165 break;
4166 }
4167 case 'v':
4168 /* Extended (long) request. */
4169 handle_v_requests (own_buf, packet_len, &new_packet_len);
4170 break;
4171
4172 default:
4173 /* It is a request we don't understand. Respond with an empty
4174 packet so that gdb knows that we don't support this
4175 request. */
4176 own_buf[0] = '\0';
4177 break;
4178 }
4179
4180 if (new_packet_len != -1)
4181 putpkt_binary (own_buf, new_packet_len);
4182 else
4183 putpkt (own_buf);
4184
4185 response_needed = 0;
4186
4187 if (!extended_protocol && have_ran && !target_running ())
4188 {
4189 /* In non-stop, defer exiting until GDB had a chance to query
4190 the whole vStopped list (until it gets an OK). */
4191 if (QUEUE_is_empty (notif_event_p, notif_stop.queue))
4192 {
4193 /* Be transparent when GDB is connected through stdio -- no
4194 need to spam GDB's console. */
4195 if (!remote_connection_is_stdio ())
4196 fprintf (stderr, "GDBserver exiting\n");
4197 remote_close ();
4198 exit (0);
4199 }
4200 }
4201
4202 if (exit_requested)
4203 return -1;
4204
4205 return 0;
4206 }
4207
4208 /* Event-loop callback for serial events. */
4209
4210 int
4211 handle_serial_event (int err, gdb_client_data client_data)
4212 {
4213 if (debug_threads)
4214 debug_printf ("handling possible serial event\n");
4215
4216 /* Really handle it. */
4217 if (process_serial_event () < 0)
4218 return -1;
4219
4220 /* Be sure to not change the selected thread behind GDB's back.
4221 Important in the non-stop mode asynchronous protocol. */
4222 set_desired_thread (1);
4223
4224 return 0;
4225 }
4226
4227 /* Event-loop callback for target events. */
4228
4229 int
4230 handle_target_event (int err, gdb_client_data client_data)
4231 {
4232 if (debug_threads)
4233 debug_printf ("handling possible target event\n");
4234
4235 last_ptid = mywait (minus_one_ptid, &last_status,
4236 TARGET_WNOHANG, 1);
4237
4238 if (last_status.kind == TARGET_WAITKIND_NO_RESUMED)
4239 {
4240 /* No RSP support for this yet. */
4241 }
4242 else if (last_status.kind != TARGET_WAITKIND_IGNORE)
4243 {
4244 int pid = ptid_get_pid (last_ptid);
4245 struct process_info *process = find_process_pid (pid);
4246 int forward_event = !gdb_connected () || process->gdb_detached;
4247
4248 if (last_status.kind == TARGET_WAITKIND_EXITED
4249 || last_status.kind == TARGET_WAITKIND_SIGNALLED)
4250 {
4251 mark_breakpoints_out (process);
4252 mourn_inferior (process);
4253 }
4254 else
4255 {
4256 /* We're reporting this thread as stopped. Update its
4257 "want-stopped" state to what the client wants, until it
4258 gets a new resume action. */
4259 current_thread->last_resume_kind = resume_stop;
4260 current_thread->last_status = last_status;
4261 }
4262
4263 if (forward_event)
4264 {
4265 if (!target_running ())
4266 {
4267 /* The last process exited. We're done. */
4268 exit (0);
4269 }
4270
4271 if (last_status.kind == TARGET_WAITKIND_STOPPED)
4272 {
4273 /* A thread stopped with a signal, but gdb isn't
4274 connected to handle it. Pass it down to the
4275 inferior, as if it wasn't being traced. */
4276 struct thread_resume resume_info;
4277
4278 if (debug_threads)
4279 debug_printf ("GDB not connected; forwarding event %d for"
4280 " [%s]\n",
4281 (int) last_status.kind,
4282 target_pid_to_str (last_ptid));
4283
4284 resume_info.thread = last_ptid;
4285 resume_info.kind = resume_continue;
4286 resume_info.sig = gdb_signal_to_host (last_status.value.sig);
4287 (*the_target->resume) (&resume_info, 1);
4288 }
4289 else if (debug_threads)
4290 debug_printf ("GDB not connected; ignoring event %d for [%s]\n",
4291 (int) last_status.kind,
4292 target_pid_to_str (last_ptid));
4293 }
4294 else
4295 {
4296 struct vstop_notif *vstop_notif = XNEW (struct vstop_notif);
4297
4298 vstop_notif->status = last_status;
4299 vstop_notif->ptid = last_ptid;
4300 /* Push Stop notification. */
4301 notif_push (&notif_stop,
4302 (struct notif_event *) vstop_notif);
4303 }
4304 }
4305
4306 /* Be sure to not change the selected thread behind GDB's back.
4307 Important in the non-stop mode asynchronous protocol. */
4308 set_desired_thread (1);
4309
4310 return 0;
4311 }