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