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