Locate executables on remote stubs without multiprocess extensions
[deliverable/binutils-gdb.git] / gdb / gdbserver / server.c
1 /* Main code for remote server for GDB.
2 Copyright (C) 1989-2015 Free Software Foundation, Inc.
3
4 This file is part of GDB.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18
19 #include "server.h"
20 #include "gdbthread.h"
21 #include "agent.h"
22 #include "notif.h"
23 #include "tdesc.h"
24 #include "rsp-low.h"
25
26 #include <ctype.h>
27 #include <unistd.h>
28 #if HAVE_SIGNAL_H
29 #include <signal.h>
30 #endif
31 #include "gdb_vecs.h"
32 #include "gdb_wait.h"
33 #include "btrace-common.h"
34 #include "filestuff.h"
35 #include "tracepoint.h"
36 #include "dll.h"
37 #include "hostio.h"
38
39 /* The thread set with an `Hc' packet. `Hc' is deprecated in favor of
40 `vCont'. Note the multi-process extensions made `vCont' a
41 requirement, so `Hc pPID.TID' is pretty much undefined. So
42 CONT_THREAD can be null_ptid for no `Hc' thread, minus_one_ptid for
43 resuming all threads of the process (again, `Hc' isn't used for
44 multi-process), or a specific thread ptid_t. */
45 ptid_t cont_thread;
46
47 /* The thread set with an `Hg' packet. */
48 ptid_t general_thread;
49
50 int server_waiting;
51
52 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 *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 if (const_annex[0] == '\0')
1157 {
1158 if (current_thread == NULL)
1159 return -1;
1160
1161 pid = pid_of (current_thread);
1162 }
1163 else
1164 {
1165 char *annex = alloca (strlen (const_annex) + 1);
1166
1167 strcpy (annex, const_annex);
1168 annex = unpack_varlen_hex (annex, &pid);
1169
1170 if (annex[0] != '\0')
1171 return -1;
1172 }
1173
1174 if (pid <= 0)
1175 return -1;
1176
1177 file = (*the_target->pid_to_exec_file) (pid);
1178 if (file == NULL)
1179 return -1;
1180
1181 total_len = strlen (file);
1182
1183 if (offset > total_len)
1184 return -1;
1185
1186 if (offset + len > total_len)
1187 len = total_len - offset;
1188
1189 memcpy (readbuf, file + offset, len);
1190 return len;
1191 }
1192
1193 /* Handle qXfer:features:read. */
1194
1195 static int
1196 handle_qxfer_features (const char *annex,
1197 gdb_byte *readbuf, const gdb_byte *writebuf,
1198 ULONGEST offset, LONGEST len)
1199 {
1200 const char *document;
1201 size_t total_len;
1202
1203 if (writebuf != NULL)
1204 return -2;
1205
1206 if (!target_running ())
1207 return -1;
1208
1209 /* Grab the correct annex. */
1210 document = get_features_xml (annex);
1211 if (document == NULL)
1212 return -1;
1213
1214 total_len = strlen (document);
1215
1216 if (offset > total_len)
1217 return -1;
1218
1219 if (offset + len > total_len)
1220 len = total_len - offset;
1221
1222 memcpy (readbuf, document + offset, len);
1223 return len;
1224 }
1225
1226 /* Worker routine for handle_qxfer_libraries.
1227 Add to the length pointed to by ARG a conservative estimate of the
1228 length needed to transmit the file name of INF. */
1229
1230 static void
1231 accumulate_file_name_length (struct inferior_list_entry *inf, void *arg)
1232 {
1233 struct dll_info *dll = (struct dll_info *) inf;
1234 unsigned int *total_len = arg;
1235
1236 /* Over-estimate the necessary memory. Assume that every character
1237 in the library name must be escaped. */
1238 *total_len += 128 + 6 * strlen (dll->name);
1239 }
1240
1241 /* Worker routine for handle_qxfer_libraries.
1242 Emit the XML to describe the library in INF. */
1243
1244 static void
1245 emit_dll_description (struct inferior_list_entry *inf, void *arg)
1246 {
1247 struct dll_info *dll = (struct dll_info *) inf;
1248 char **p_ptr = arg;
1249 char *p = *p_ptr;
1250 char *name;
1251
1252 strcpy (p, " <library name=\"");
1253 p = p + strlen (p);
1254 name = xml_escape_text (dll->name);
1255 strcpy (p, name);
1256 free (name);
1257 p = p + strlen (p);
1258 strcpy (p, "\"><segment address=\"");
1259 p = p + strlen (p);
1260 sprintf (p, "0x%lx", (long) dll->base_addr);
1261 p = p + strlen (p);
1262 strcpy (p, "\"/></library>\n");
1263 p = p + strlen (p);
1264
1265 *p_ptr = p;
1266 }
1267
1268 /* Handle qXfer:libraries:read. */
1269
1270 static int
1271 handle_qxfer_libraries (const char *annex,
1272 gdb_byte *readbuf, const gdb_byte *writebuf,
1273 ULONGEST offset, LONGEST len)
1274 {
1275 unsigned int total_len;
1276 char *document, *p;
1277
1278 if (writebuf != NULL)
1279 return -2;
1280
1281 if (annex[0] != '\0' || !target_running ())
1282 return -1;
1283
1284 total_len = 64;
1285 for_each_inferior_with_data (&all_dlls, accumulate_file_name_length,
1286 &total_len);
1287
1288 document = malloc (total_len);
1289 if (document == NULL)
1290 return -1;
1291
1292 strcpy (document, "<library-list>\n");
1293 p = document + strlen (document);
1294
1295 for_each_inferior_with_data (&all_dlls, emit_dll_description, &p);
1296
1297 strcpy (p, "</library-list>\n");
1298
1299 total_len = strlen (document);
1300
1301 if (offset > total_len)
1302 {
1303 free (document);
1304 return -1;
1305 }
1306
1307 if (offset + len > total_len)
1308 len = total_len - offset;
1309
1310 memcpy (readbuf, document + offset, len);
1311 free (document);
1312 return len;
1313 }
1314
1315 /* Handle qXfer:libraries-svr4:read. */
1316
1317 static int
1318 handle_qxfer_libraries_svr4 (const char *annex,
1319 gdb_byte *readbuf, const gdb_byte *writebuf,
1320 ULONGEST offset, LONGEST len)
1321 {
1322 if (writebuf != NULL)
1323 return -2;
1324
1325 if (!target_running () || the_target->qxfer_libraries_svr4 == NULL)
1326 return -1;
1327
1328 return the_target->qxfer_libraries_svr4 (annex, readbuf, writebuf, offset, len);
1329 }
1330
1331 /* Handle qXfer:osadata:read. */
1332
1333 static int
1334 handle_qxfer_osdata (const char *annex,
1335 gdb_byte *readbuf, const gdb_byte *writebuf,
1336 ULONGEST offset, LONGEST len)
1337 {
1338 if (the_target->qxfer_osdata == NULL || writebuf != NULL)
1339 return -2;
1340
1341 return (*the_target->qxfer_osdata) (annex, readbuf, NULL, offset, len);
1342 }
1343
1344 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1345
1346 static int
1347 handle_qxfer_siginfo (const char *annex,
1348 gdb_byte *readbuf, const gdb_byte *writebuf,
1349 ULONGEST offset, LONGEST len)
1350 {
1351 if (the_target->qxfer_siginfo == NULL)
1352 return -2;
1353
1354 if (annex[0] != '\0' || !target_running ())
1355 return -1;
1356
1357 return (*the_target->qxfer_siginfo) (annex, readbuf, writebuf, offset, len);
1358 }
1359
1360 /* Handle qXfer:spu:read and qXfer:spu:write. */
1361
1362 static int
1363 handle_qxfer_spu (const char *annex,
1364 gdb_byte *readbuf, const gdb_byte *writebuf,
1365 ULONGEST offset, LONGEST len)
1366 {
1367 if (the_target->qxfer_spu == NULL)
1368 return -2;
1369
1370 if (!target_running ())
1371 return -1;
1372
1373 return (*the_target->qxfer_spu) (annex, readbuf, writebuf, offset, len);
1374 }
1375
1376 /* Handle qXfer:statictrace:read. */
1377
1378 static int
1379 handle_qxfer_statictrace (const char *annex,
1380 gdb_byte *readbuf, const gdb_byte *writebuf,
1381 ULONGEST offset, LONGEST len)
1382 {
1383 ULONGEST nbytes;
1384
1385 if (writebuf != NULL)
1386 return -2;
1387
1388 if (annex[0] != '\0' || !target_running () || current_traceframe == -1)
1389 return -1;
1390
1391 if (traceframe_read_sdata (current_traceframe, offset,
1392 readbuf, len, &nbytes))
1393 return -1;
1394 return nbytes;
1395 }
1396
1397 /* Helper for handle_qxfer_threads_proper.
1398 Emit the XML to describe the thread of INF. */
1399
1400 static void
1401 handle_qxfer_threads_worker (struct inferior_list_entry *inf, void *arg)
1402 {
1403 struct thread_info *thread = (struct thread_info *) inf;
1404 struct buffer *buffer = arg;
1405 ptid_t ptid = thread_to_gdb_id (thread);
1406 char ptid_s[100];
1407 int core = target_core_of_thread (ptid);
1408 char core_s[21];
1409
1410 write_ptid (ptid_s, ptid);
1411
1412 if (core != -1)
1413 {
1414 sprintf (core_s, "%d", core);
1415 buffer_xml_printf (buffer, "<thread id=\"%s\" core=\"%s\"/>\n",
1416 ptid_s, core_s);
1417 }
1418 else
1419 {
1420 buffer_xml_printf (buffer, "<thread id=\"%s\"/>\n",
1421 ptid_s);
1422 }
1423 }
1424
1425 /* Helper for handle_qxfer_threads. */
1426
1427 static void
1428 handle_qxfer_threads_proper (struct buffer *buffer)
1429 {
1430 buffer_grow_str (buffer, "<threads>\n");
1431
1432 for_each_inferior_with_data (&all_threads, handle_qxfer_threads_worker,
1433 buffer);
1434
1435 buffer_grow_str0 (buffer, "</threads>\n");
1436 }
1437
1438 /* Handle qXfer:threads:read. */
1439
1440 static int
1441 handle_qxfer_threads (const char *annex,
1442 gdb_byte *readbuf, const gdb_byte *writebuf,
1443 ULONGEST offset, LONGEST len)
1444 {
1445 static char *result = 0;
1446 static unsigned int result_length = 0;
1447
1448 if (writebuf != NULL)
1449 return -2;
1450
1451 if (!target_running () || annex[0] != '\0')
1452 return -1;
1453
1454 if (offset == 0)
1455 {
1456 struct buffer buffer;
1457 /* When asked for data at offset 0, generate everything and store into
1458 'result'. Successive reads will be served off 'result'. */
1459 if (result)
1460 free (result);
1461
1462 buffer_init (&buffer);
1463
1464 handle_qxfer_threads_proper (&buffer);
1465
1466 result = buffer_finish (&buffer);
1467 result_length = strlen (result);
1468 buffer_free (&buffer);
1469 }
1470
1471 if (offset >= result_length)
1472 {
1473 /* We're out of data. */
1474 free (result);
1475 result = NULL;
1476 result_length = 0;
1477 return 0;
1478 }
1479
1480 if (len > result_length - offset)
1481 len = result_length - offset;
1482
1483 memcpy (readbuf, result + offset, len);
1484
1485 return len;
1486 }
1487
1488 /* Handle qXfer:traceframe-info:read. */
1489
1490 static int
1491 handle_qxfer_traceframe_info (const char *annex,
1492 gdb_byte *readbuf, const gdb_byte *writebuf,
1493 ULONGEST offset, LONGEST len)
1494 {
1495 static char *result = 0;
1496 static unsigned int result_length = 0;
1497
1498 if (writebuf != NULL)
1499 return -2;
1500
1501 if (!target_running () || annex[0] != '\0' || current_traceframe == -1)
1502 return -1;
1503
1504 if (offset == 0)
1505 {
1506 struct buffer buffer;
1507
1508 /* When asked for data at offset 0, generate everything and
1509 store into 'result'. Successive reads will be served off
1510 'result'. */
1511 free (result);
1512
1513 buffer_init (&buffer);
1514
1515 traceframe_read_info (current_traceframe, &buffer);
1516
1517 result = buffer_finish (&buffer);
1518 result_length = strlen (result);
1519 buffer_free (&buffer);
1520 }
1521
1522 if (offset >= result_length)
1523 {
1524 /* We're out of data. */
1525 free (result);
1526 result = NULL;
1527 result_length = 0;
1528 return 0;
1529 }
1530
1531 if (len > result_length - offset)
1532 len = result_length - offset;
1533
1534 memcpy (readbuf, result + offset, len);
1535 return len;
1536 }
1537
1538 /* Handle qXfer:fdpic:read. */
1539
1540 static int
1541 handle_qxfer_fdpic (const char *annex, gdb_byte *readbuf,
1542 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
1543 {
1544 if (the_target->read_loadmap == NULL)
1545 return -2;
1546
1547 if (!target_running ())
1548 return -1;
1549
1550 return (*the_target->read_loadmap) (annex, offset, readbuf, len);
1551 }
1552
1553 /* Handle qXfer:btrace:read. */
1554
1555 static int
1556 handle_qxfer_btrace (const char *annex,
1557 gdb_byte *readbuf, const gdb_byte *writebuf,
1558 ULONGEST offset, LONGEST len)
1559 {
1560 static struct buffer cache;
1561 struct thread_info *thread;
1562 int type, result;
1563
1564 if (the_target->read_btrace == NULL || writebuf != NULL)
1565 return -2;
1566
1567 if (!target_running ())
1568 return -1;
1569
1570 if (ptid_equal (general_thread, null_ptid)
1571 || ptid_equal (general_thread, minus_one_ptid))
1572 {
1573 strcpy (own_buf, "E.Must select a single thread.");
1574 return -3;
1575 }
1576
1577 thread = find_thread_ptid (general_thread);
1578 if (thread == NULL)
1579 {
1580 strcpy (own_buf, "E.No such thread.");
1581 return -3;
1582 }
1583
1584 if (thread->btrace == NULL)
1585 {
1586 strcpy (own_buf, "E.Btrace not enabled.");
1587 return -3;
1588 }
1589
1590 if (strcmp (annex, "all") == 0)
1591 type = BTRACE_READ_ALL;
1592 else if (strcmp (annex, "new") == 0)
1593 type = BTRACE_READ_NEW;
1594 else if (strcmp (annex, "delta") == 0)
1595 type = BTRACE_READ_DELTA;
1596 else
1597 {
1598 strcpy (own_buf, "E.Bad annex.");
1599 return -3;
1600 }
1601
1602 if (offset == 0)
1603 {
1604 buffer_free (&cache);
1605
1606 result = target_read_btrace (thread->btrace, &cache, type);
1607 if (result != 0)
1608 {
1609 memcpy (own_buf, cache.buffer, cache.used_size);
1610 return -3;
1611 }
1612 }
1613 else if (offset > cache.used_size)
1614 {
1615 buffer_free (&cache);
1616 return -3;
1617 }
1618
1619 if (len > cache.used_size - offset)
1620 len = cache.used_size - offset;
1621
1622 memcpy (readbuf, cache.buffer + offset, len);
1623
1624 return len;
1625 }
1626
1627 /* Handle qXfer:btrace-conf:read. */
1628
1629 static int
1630 handle_qxfer_btrace_conf (const char *annex,
1631 gdb_byte *readbuf, const gdb_byte *writebuf,
1632 ULONGEST offset, LONGEST len)
1633 {
1634 static struct buffer cache;
1635 struct thread_info *thread;
1636 int result;
1637
1638 if (the_target->read_btrace_conf == NULL || writebuf != NULL)
1639 return -2;
1640
1641 if (annex[0] != '\0' || !target_running ())
1642 return -1;
1643
1644 if (ptid_equal (general_thread, null_ptid)
1645 || ptid_equal (general_thread, minus_one_ptid))
1646 {
1647 strcpy (own_buf, "E.Must select a single thread.");
1648 return -3;
1649 }
1650
1651 thread = find_thread_ptid (general_thread);
1652 if (thread == NULL)
1653 {
1654 strcpy (own_buf, "E.No such thread.");
1655 return -3;
1656 }
1657
1658 if (thread->btrace == NULL)
1659 {
1660 strcpy (own_buf, "E.Btrace not enabled.");
1661 return -3;
1662 }
1663
1664 if (offset == 0)
1665 {
1666 buffer_free (&cache);
1667
1668 result = target_read_btrace_conf (thread->btrace, &cache);
1669 if (result != 0)
1670 {
1671 memcpy (own_buf, cache.buffer, cache.used_size);
1672 return -3;
1673 }
1674 }
1675 else if (offset > cache.used_size)
1676 {
1677 buffer_free (&cache);
1678 return -3;
1679 }
1680
1681 if (len > cache.used_size - offset)
1682 len = cache.used_size - offset;
1683
1684 memcpy (readbuf, cache.buffer + offset, len);
1685
1686 return len;
1687 }
1688
1689 static const struct qxfer qxfer_packets[] =
1690 {
1691 { "auxv", handle_qxfer_auxv },
1692 { "btrace", handle_qxfer_btrace },
1693 { "btrace-conf", handle_qxfer_btrace_conf },
1694 { "exec-file", handle_qxfer_exec_file},
1695 { "fdpic", handle_qxfer_fdpic},
1696 { "features", handle_qxfer_features },
1697 { "libraries", handle_qxfer_libraries },
1698 { "libraries-svr4", handle_qxfer_libraries_svr4 },
1699 { "osdata", handle_qxfer_osdata },
1700 { "siginfo", handle_qxfer_siginfo },
1701 { "spu", handle_qxfer_spu },
1702 { "statictrace", handle_qxfer_statictrace },
1703 { "threads", handle_qxfer_threads },
1704 { "traceframe-info", handle_qxfer_traceframe_info },
1705 };
1706
1707 static int
1708 handle_qxfer (char *own_buf, int packet_len, int *new_packet_len_p)
1709 {
1710 int i;
1711 char *object;
1712 char *rw;
1713 char *annex;
1714 char *offset;
1715
1716 if (!startswith (own_buf, "qXfer:"))
1717 return 0;
1718
1719 /* Grab the object, r/w and annex. */
1720 if (decode_xfer (own_buf + 6, &object, &rw, &annex, &offset) < 0)
1721 {
1722 write_enn (own_buf);
1723 return 1;
1724 }
1725
1726 for (i = 0;
1727 i < sizeof (qxfer_packets) / sizeof (qxfer_packets[0]);
1728 i++)
1729 {
1730 const struct qxfer *q = &qxfer_packets[i];
1731
1732 if (strcmp (object, q->object) == 0)
1733 {
1734 if (strcmp (rw, "read") == 0)
1735 {
1736 unsigned char *data;
1737 int n;
1738 CORE_ADDR ofs;
1739 unsigned int len;
1740
1741 /* Grab the offset and length. */
1742 if (decode_xfer_read (offset, &ofs, &len) < 0)
1743 {
1744 write_enn (own_buf);
1745 return 1;
1746 }
1747
1748 /* Read one extra byte, as an indicator of whether there is
1749 more. */
1750 if (len > PBUFSIZ - 2)
1751 len = PBUFSIZ - 2;
1752 data = malloc (len + 1);
1753 if (data == NULL)
1754 {
1755 write_enn (own_buf);
1756 return 1;
1757 }
1758 n = (*q->xfer) (annex, data, NULL, ofs, len + 1);
1759 if (n == -2)
1760 {
1761 free (data);
1762 return 0;
1763 }
1764 else if (n == -3)
1765 {
1766 /* Preserve error message. */
1767 }
1768 else if (n < 0)
1769 write_enn (own_buf);
1770 else if (n > len)
1771 *new_packet_len_p = write_qxfer_response (own_buf, data, len, 1);
1772 else
1773 *new_packet_len_p = write_qxfer_response (own_buf, data, n, 0);
1774
1775 free (data);
1776 return 1;
1777 }
1778 else if (strcmp (rw, "write") == 0)
1779 {
1780 int n;
1781 unsigned int len;
1782 CORE_ADDR ofs;
1783 unsigned char *data;
1784
1785 strcpy (own_buf, "E00");
1786 data = malloc (packet_len - (offset - own_buf));
1787 if (data == NULL)
1788 {
1789 write_enn (own_buf);
1790 return 1;
1791 }
1792 if (decode_xfer_write (offset, packet_len - (offset - own_buf),
1793 &ofs, &len, data) < 0)
1794 {
1795 free (data);
1796 write_enn (own_buf);
1797 return 1;
1798 }
1799
1800 n = (*q->xfer) (annex, NULL, data, ofs, len);
1801 if (n == -2)
1802 {
1803 free (data);
1804 return 0;
1805 }
1806 else if (n == -3)
1807 {
1808 /* Preserve error message. */
1809 }
1810 else if (n < 0)
1811 write_enn (own_buf);
1812 else
1813 sprintf (own_buf, "%x", n);
1814
1815 free (data);
1816 return 1;
1817 }
1818
1819 return 0;
1820 }
1821 }
1822
1823 return 0;
1824 }
1825
1826 /* Table used by the crc32 function to calcuate the checksum. */
1827
1828 static unsigned int crc32_table[256] =
1829 {0, 0};
1830
1831 /* Compute 32 bit CRC from inferior memory.
1832
1833 On success, return 32 bit CRC.
1834 On failure, return (unsigned long long) -1. */
1835
1836 static unsigned long long
1837 crc32 (CORE_ADDR base, int len, unsigned int crc)
1838 {
1839 if (!crc32_table[1])
1840 {
1841 /* Initialize the CRC table and the decoding table. */
1842 int i, j;
1843 unsigned int c;
1844
1845 for (i = 0; i < 256; i++)
1846 {
1847 for (c = i << 24, j = 8; j > 0; --j)
1848 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
1849 crc32_table[i] = c;
1850 }
1851 }
1852
1853 while (len--)
1854 {
1855 unsigned char byte = 0;
1856
1857 /* Return failure if memory read fails. */
1858 if (read_inferior_memory (base, &byte, 1) != 0)
1859 return (unsigned long long) -1;
1860
1861 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ byte) & 255];
1862 base++;
1863 }
1864 return (unsigned long long) crc;
1865 }
1866
1867 /* Add supported btrace packets to BUF. */
1868
1869 static void
1870 supported_btrace_packets (char *buf)
1871 {
1872 if (target_supports_btrace (BTRACE_FORMAT_BTS))
1873 {
1874 strcat (buf, ";Qbtrace:bts+");
1875 strcat (buf, ";Qbtrace-conf:bts:size+");
1876 }
1877 else
1878 return;
1879
1880 strcat (buf, ";Qbtrace:off+");
1881 strcat (buf, ";qXfer:btrace:read+");
1882 strcat (buf, ";qXfer:btrace-conf:read+");
1883 }
1884
1885 /* Handle all of the extended 'q' packets. */
1886
1887 void
1888 handle_query (char *own_buf, int packet_len, int *new_packet_len_p)
1889 {
1890 static struct inferior_list_entry *thread_ptr;
1891
1892 /* Reply the current thread id. */
1893 if (strcmp ("qC", own_buf) == 0 && !disable_packet_qC)
1894 {
1895 ptid_t gdb_id;
1896 require_running (own_buf);
1897
1898 if (!ptid_equal (general_thread, null_ptid)
1899 && !ptid_equal (general_thread, minus_one_ptid))
1900 gdb_id = general_thread;
1901 else
1902 {
1903 thread_ptr = get_first_inferior (&all_threads);
1904 gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
1905 }
1906
1907 sprintf (own_buf, "QC");
1908 own_buf += 2;
1909 write_ptid (own_buf, gdb_id);
1910 return;
1911 }
1912
1913 if (strcmp ("qSymbol::", own_buf) == 0)
1914 {
1915 /* GDB is suggesting new symbols have been loaded. This may
1916 mean a new shared library has been detected as loaded, so
1917 take the opportunity to check if breakpoints we think are
1918 inserted, still are. Note that it isn't guaranteed that
1919 we'll see this when a shared library is loaded, and nor will
1920 we see this for unloads (although breakpoints in unloaded
1921 libraries shouldn't trigger), as GDB may not find symbols for
1922 the library at all. We also re-validate breakpoints when we
1923 see a second GDB breakpoint for the same address, and or when
1924 we access breakpoint shadows. */
1925 validate_breakpoints ();
1926
1927 if (target_supports_tracepoints ())
1928 tracepoint_look_up_symbols ();
1929
1930 if (target_running () && the_target->look_up_symbols != NULL)
1931 (*the_target->look_up_symbols) ();
1932
1933 strcpy (own_buf, "OK");
1934 return;
1935 }
1936
1937 if (!disable_packet_qfThreadInfo)
1938 {
1939 if (strcmp ("qfThreadInfo", own_buf) == 0)
1940 {
1941 ptid_t gdb_id;
1942
1943 require_running (own_buf);
1944 thread_ptr = get_first_inferior (&all_threads);
1945
1946 *own_buf++ = 'm';
1947 gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
1948 write_ptid (own_buf, gdb_id);
1949 thread_ptr = thread_ptr->next;
1950 return;
1951 }
1952
1953 if (strcmp ("qsThreadInfo", own_buf) == 0)
1954 {
1955 ptid_t gdb_id;
1956
1957 require_running (own_buf);
1958 if (thread_ptr != NULL)
1959 {
1960 *own_buf++ = 'm';
1961 gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
1962 write_ptid (own_buf, gdb_id);
1963 thread_ptr = thread_ptr->next;
1964 return;
1965 }
1966 else
1967 {
1968 sprintf (own_buf, "l");
1969 return;
1970 }
1971 }
1972 }
1973
1974 if (the_target->read_offsets != NULL
1975 && strcmp ("qOffsets", own_buf) == 0)
1976 {
1977 CORE_ADDR text, data;
1978
1979 require_running (own_buf);
1980 if (the_target->read_offsets (&text, &data))
1981 sprintf (own_buf, "Text=%lX;Data=%lX;Bss=%lX",
1982 (long)text, (long)data, (long)data);
1983 else
1984 write_enn (own_buf);
1985
1986 return;
1987 }
1988
1989 /* Protocol features query. */
1990 if (startswith (own_buf, "qSupported")
1991 && (own_buf[10] == ':' || own_buf[10] == '\0'))
1992 {
1993 char *p = &own_buf[10];
1994 int gdb_supports_qRelocInsn = 0;
1995
1996 /* Start processing qSupported packet. */
1997 target_process_qsupported (NULL);
1998
1999 /* Process each feature being provided by GDB. The first
2000 feature will follow a ':', and latter features will follow
2001 ';'. */
2002 if (*p == ':')
2003 {
2004 char **qsupported = NULL;
2005 int count = 0;
2006 int i;
2007
2008 /* Two passes, to avoid nested strtok calls in
2009 target_process_qsupported. */
2010 for (p = strtok (p + 1, ";");
2011 p != NULL;
2012 p = strtok (NULL, ";"))
2013 {
2014 count++;
2015 qsupported = xrealloc (qsupported, count * sizeof (char *));
2016 qsupported[count - 1] = xstrdup (p);
2017 }
2018
2019 for (i = 0; i < count; i++)
2020 {
2021 p = qsupported[i];
2022 if (strcmp (p, "multiprocess+") == 0)
2023 {
2024 /* GDB supports and wants multi-process support if
2025 possible. */
2026 if (target_supports_multi_process ())
2027 multi_process = 1;
2028 }
2029 else if (strcmp (p, "qRelocInsn+") == 0)
2030 {
2031 /* GDB supports relocate instruction requests. */
2032 gdb_supports_qRelocInsn = 1;
2033 }
2034 else if (strcmp (p, "swbreak+") == 0)
2035 {
2036 /* GDB wants us to report whether a trap is caused
2037 by a software breakpoint and for us to handle PC
2038 adjustment if necessary on this target. */
2039 if (target_supports_stopped_by_sw_breakpoint ())
2040 swbreak_feature = 1;
2041 }
2042 else if (strcmp (p, "hwbreak+") == 0)
2043 {
2044 /* GDB wants us to report whether a trap is caused
2045 by a hardware breakpoint. */
2046 if (target_supports_stopped_by_hw_breakpoint ())
2047 hwbreak_feature = 1;
2048 }
2049 else
2050 target_process_qsupported (p);
2051
2052 free (p);
2053 }
2054
2055 free (qsupported);
2056 }
2057
2058 sprintf (own_buf,
2059 "PacketSize=%x;QPassSignals+;QProgramSignals+",
2060 PBUFSIZ - 1);
2061
2062 if (the_target->qxfer_libraries_svr4 != NULL)
2063 strcat (own_buf, ";qXfer:libraries-svr4:read+"
2064 ";augmented-libraries-svr4-read+");
2065 else
2066 {
2067 /* We do not have any hook to indicate whether the non-SVR4 target
2068 backend supports qXfer:libraries:read, so always report it. */
2069 strcat (own_buf, ";qXfer:libraries:read+");
2070 }
2071
2072 if (the_target->read_auxv != NULL)
2073 strcat (own_buf, ";qXfer:auxv:read+");
2074
2075 if (the_target->qxfer_spu != NULL)
2076 strcat (own_buf, ";qXfer:spu:read+;qXfer:spu:write+");
2077
2078 if (the_target->qxfer_siginfo != NULL)
2079 strcat (own_buf, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2080
2081 if (the_target->read_loadmap != NULL)
2082 strcat (own_buf, ";qXfer:fdpic:read+");
2083
2084 /* We always report qXfer:features:read, as targets may
2085 install XML files on a subsequent call to arch_setup.
2086 If we reported to GDB on startup that we don't support
2087 qXfer:feature:read at all, we will never be re-queried. */
2088 strcat (own_buf, ";qXfer:features:read+");
2089
2090 if (transport_is_reliable)
2091 strcat (own_buf, ";QStartNoAckMode+");
2092
2093 if (the_target->qxfer_osdata != NULL)
2094 strcat (own_buf, ";qXfer:osdata:read+");
2095
2096 if (target_supports_multi_process ())
2097 strcat (own_buf, ";multiprocess+");
2098
2099 if (target_supports_non_stop ())
2100 strcat (own_buf, ";QNonStop+");
2101
2102 if (target_supports_disable_randomization ())
2103 strcat (own_buf, ";QDisableRandomization+");
2104
2105 strcat (own_buf, ";qXfer:threads:read+");
2106
2107 if (target_supports_tracepoints ())
2108 {
2109 strcat (own_buf, ";ConditionalTracepoints+");
2110 strcat (own_buf, ";TraceStateVariables+");
2111 strcat (own_buf, ";TracepointSource+");
2112 strcat (own_buf, ";DisconnectedTracing+");
2113 if (gdb_supports_qRelocInsn && target_supports_fast_tracepoints ())
2114 strcat (own_buf, ";FastTracepoints+");
2115 strcat (own_buf, ";StaticTracepoints+");
2116 strcat (own_buf, ";InstallInTrace+");
2117 strcat (own_buf, ";qXfer:statictrace:read+");
2118 strcat (own_buf, ";qXfer:traceframe-info:read+");
2119 strcat (own_buf, ";EnableDisableTracepoints+");
2120 strcat (own_buf, ";QTBuffer:size+");
2121 strcat (own_buf, ";tracenz+");
2122 }
2123
2124 /* Support target-side breakpoint conditions and commands. */
2125 if (target_supports_conditional_breakpoints ())
2126 strcat (own_buf, ";ConditionalBreakpoints+");
2127 strcat (own_buf, ";BreakpointCommands+");
2128
2129 if (target_supports_agent ())
2130 strcat (own_buf, ";QAgent+");
2131
2132 supported_btrace_packets (own_buf);
2133
2134 if (target_supports_stopped_by_sw_breakpoint ())
2135 strcat (own_buf, ";swbreak+");
2136
2137 if (target_supports_stopped_by_hw_breakpoint ())
2138 strcat (own_buf, ";hwbreak+");
2139
2140 if (the_target->pid_to_exec_file != NULL)
2141 strcat (own_buf, ";qXfer:exec-file:read+");
2142
2143 return;
2144 }
2145
2146 /* Thread-local storage support. */
2147 if (the_target->get_tls_address != NULL
2148 && startswith (own_buf, "qGetTLSAddr:"))
2149 {
2150 char *p = own_buf + 12;
2151 CORE_ADDR parts[2], address = 0;
2152 int i, err;
2153 ptid_t ptid = null_ptid;
2154
2155 require_running (own_buf);
2156
2157 for (i = 0; i < 3; i++)
2158 {
2159 char *p2;
2160 int len;
2161
2162 if (p == NULL)
2163 break;
2164
2165 p2 = strchr (p, ',');
2166 if (p2)
2167 {
2168 len = p2 - p;
2169 p2++;
2170 }
2171 else
2172 {
2173 len = strlen (p);
2174 p2 = NULL;
2175 }
2176
2177 if (i == 0)
2178 ptid = read_ptid (p, NULL);
2179 else
2180 decode_address (&parts[i - 1], p, len);
2181 p = p2;
2182 }
2183
2184 if (p != NULL || i < 3)
2185 err = 1;
2186 else
2187 {
2188 struct thread_info *thread = find_thread_ptid (ptid);
2189
2190 if (thread == NULL)
2191 err = 2;
2192 else
2193 err = the_target->get_tls_address (thread, parts[0], parts[1],
2194 &address);
2195 }
2196
2197 if (err == 0)
2198 {
2199 strcpy (own_buf, paddress(address));
2200 return;
2201 }
2202 else if (err > 0)
2203 {
2204 write_enn (own_buf);
2205 return;
2206 }
2207
2208 /* Otherwise, pretend we do not understand this packet. */
2209 }
2210
2211 /* Windows OS Thread Information Block address support. */
2212 if (the_target->get_tib_address != NULL
2213 && startswith (own_buf, "qGetTIBAddr:"))
2214 {
2215 char *annex;
2216 int n;
2217 CORE_ADDR tlb;
2218 ptid_t ptid = read_ptid (own_buf + 12, &annex);
2219
2220 n = (*the_target->get_tib_address) (ptid, &tlb);
2221 if (n == 1)
2222 {
2223 strcpy (own_buf, paddress(tlb));
2224 return;
2225 }
2226 else if (n == 0)
2227 {
2228 write_enn (own_buf);
2229 return;
2230 }
2231 return;
2232 }
2233
2234 /* Handle "monitor" commands. */
2235 if (startswith (own_buf, "qRcmd,"))
2236 {
2237 char *mon = malloc (PBUFSIZ);
2238 int len = strlen (own_buf + 6);
2239
2240 if (mon == NULL)
2241 {
2242 write_enn (own_buf);
2243 return;
2244 }
2245
2246 if ((len % 2) != 0
2247 || hex2bin (own_buf + 6, (gdb_byte *) mon, len / 2) != len / 2)
2248 {
2249 write_enn (own_buf);
2250 free (mon);
2251 return;
2252 }
2253 mon[len / 2] = '\0';
2254
2255 write_ok (own_buf);
2256
2257 if (the_target->handle_monitor_command == NULL
2258 || (*the_target->handle_monitor_command) (mon) == 0)
2259 /* Default processing. */
2260 handle_monitor_command (mon, own_buf);
2261
2262 free (mon);
2263 return;
2264 }
2265
2266 if (startswith (own_buf, "qSearch:memory:"))
2267 {
2268 require_running (own_buf);
2269 handle_search_memory (own_buf, packet_len);
2270 return;
2271 }
2272
2273 if (strcmp (own_buf, "qAttached") == 0
2274 || startswith (own_buf, "qAttached:"))
2275 {
2276 struct process_info *process;
2277
2278 if (own_buf[sizeof ("qAttached") - 1])
2279 {
2280 int pid = strtoul (own_buf + sizeof ("qAttached:") - 1, NULL, 16);
2281 process = (struct process_info *)
2282 find_inferior_id (&all_processes, pid_to_ptid (pid));
2283 }
2284 else
2285 {
2286 require_running (own_buf);
2287 process = current_process ();
2288 }
2289
2290 if (process == NULL)
2291 {
2292 write_enn (own_buf);
2293 return;
2294 }
2295
2296 strcpy (own_buf, process->attached ? "1" : "0");
2297 return;
2298 }
2299
2300 if (startswith (own_buf, "qCRC:"))
2301 {
2302 /* CRC check (compare-section). */
2303 char *comma;
2304 ULONGEST base;
2305 int len;
2306 unsigned long long crc;
2307
2308 require_running (own_buf);
2309 comma = unpack_varlen_hex (own_buf + 5, &base);
2310 if (*comma++ != ',')
2311 {
2312 write_enn (own_buf);
2313 return;
2314 }
2315 len = strtoul (comma, NULL, 16);
2316 crc = crc32 (base, len, 0xffffffff);
2317 /* Check for memory failure. */
2318 if (crc == (unsigned long long) -1)
2319 {
2320 write_enn (own_buf);
2321 return;
2322 }
2323 sprintf (own_buf, "C%lx", (unsigned long) crc);
2324 return;
2325 }
2326
2327 if (handle_qxfer (own_buf, packet_len, new_packet_len_p))
2328 return;
2329
2330 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf))
2331 return;
2332
2333 /* Otherwise we didn't know what packet it was. Say we didn't
2334 understand it. */
2335 own_buf[0] = 0;
2336 }
2337
2338 static void gdb_wants_all_threads_stopped (void);
2339 static void resume (struct thread_resume *actions, size_t n);
2340
2341 /* The callback that is passed to visit_actioned_threads. */
2342 typedef int (visit_actioned_threads_callback_ftype)
2343 (const struct thread_resume *, struct thread_info *);
2344
2345 /* Struct to pass data to visit_actioned_threads. */
2346
2347 struct visit_actioned_threads_data
2348 {
2349 const struct thread_resume *actions;
2350 size_t num_actions;
2351 visit_actioned_threads_callback_ftype *callback;
2352 };
2353
2354 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
2355 true if CALLBACK returns true. Returns false if no matching thread
2356 is found or CALLBACK results false.
2357 Note: This function is itself a callback for find_inferior. */
2358
2359 static int
2360 visit_actioned_threads (struct inferior_list_entry *entry, void *datap)
2361 {
2362 struct visit_actioned_threads_data *data = datap;
2363 const struct thread_resume *actions = data->actions;
2364 size_t num_actions = data->num_actions;
2365 visit_actioned_threads_callback_ftype *callback = data->callback;
2366 size_t i;
2367
2368 for (i = 0; i < num_actions; i++)
2369 {
2370 const struct thread_resume *action = &actions[i];
2371
2372 if (ptid_equal (action->thread, minus_one_ptid)
2373 || ptid_equal (action->thread, entry->id)
2374 || ((ptid_get_pid (action->thread)
2375 == ptid_get_pid (entry->id))
2376 && ptid_get_lwp (action->thread) == -1))
2377 {
2378 struct thread_info *thread = (struct thread_info *) entry;
2379
2380 if ((*callback) (action, thread))
2381 return 1;
2382 }
2383 }
2384
2385 return 0;
2386 }
2387
2388 /* Callback for visit_actioned_threads. If the thread has a pending
2389 status to report, report it now. */
2390
2391 static int
2392 handle_pending_status (const struct thread_resume *resumption,
2393 struct thread_info *thread)
2394 {
2395 if (thread->status_pending_p)
2396 {
2397 thread->status_pending_p = 0;
2398
2399 last_status = thread->last_status;
2400 last_ptid = thread->entry.id;
2401 prepare_resume_reply (own_buf, last_ptid, &last_status);
2402 return 1;
2403 }
2404 return 0;
2405 }
2406
2407 /* Parse vCont packets. */
2408 void
2409 handle_v_cont (char *own_buf)
2410 {
2411 char *p, *q;
2412 int n = 0, i = 0;
2413 struct thread_resume *resume_info;
2414 struct thread_resume default_action = {{0}};
2415
2416 /* Count the number of semicolons in the packet. There should be one
2417 for every action. */
2418 p = &own_buf[5];
2419 while (p)
2420 {
2421 n++;
2422 p++;
2423 p = strchr (p, ';');
2424 }
2425
2426 resume_info = malloc (n * sizeof (resume_info[0]));
2427 if (resume_info == NULL)
2428 goto err;
2429
2430 p = &own_buf[5];
2431 while (*p)
2432 {
2433 p++;
2434
2435 memset (&resume_info[i], 0, sizeof resume_info[i]);
2436
2437 if (p[0] == 's' || p[0] == 'S')
2438 resume_info[i].kind = resume_step;
2439 else if (p[0] == 'r')
2440 resume_info[i].kind = resume_step;
2441 else if (p[0] == 'c' || p[0] == 'C')
2442 resume_info[i].kind = resume_continue;
2443 else if (p[0] == 't')
2444 resume_info[i].kind = resume_stop;
2445 else
2446 goto err;
2447
2448 if (p[0] == 'S' || p[0] == 'C')
2449 {
2450 int sig;
2451 sig = strtol (p + 1, &q, 16);
2452 if (p == q)
2453 goto err;
2454 p = q;
2455
2456 if (!gdb_signal_to_host_p (sig))
2457 goto err;
2458 resume_info[i].sig = gdb_signal_to_host (sig);
2459 }
2460 else if (p[0] == 'r')
2461 {
2462 ULONGEST addr;
2463
2464 p = unpack_varlen_hex (p + 1, &addr);
2465 resume_info[i].step_range_start = addr;
2466
2467 if (*p != ',')
2468 goto err;
2469
2470 p = unpack_varlen_hex (p + 1, &addr);
2471 resume_info[i].step_range_end = addr;
2472 }
2473 else
2474 {
2475 p = p + 1;
2476 }
2477
2478 if (p[0] == 0)
2479 {
2480 resume_info[i].thread = minus_one_ptid;
2481 default_action = resume_info[i];
2482
2483 /* Note: we don't increment i here, we'll overwrite this entry
2484 the next time through. */
2485 }
2486 else if (p[0] == ':')
2487 {
2488 ptid_t ptid = read_ptid (p + 1, &q);
2489
2490 if (p == q)
2491 goto err;
2492 p = q;
2493 if (p[0] != ';' && p[0] != 0)
2494 goto err;
2495
2496 resume_info[i].thread = ptid;
2497
2498 i++;
2499 }
2500 }
2501
2502 if (i < n)
2503 resume_info[i] = default_action;
2504
2505 set_desired_thread (0);
2506
2507 resume (resume_info, n);
2508 free (resume_info);
2509 return;
2510
2511 err:
2512 write_enn (own_buf);
2513 free (resume_info);
2514 return;
2515 }
2516
2517 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
2518
2519 static void
2520 resume (struct thread_resume *actions, size_t num_actions)
2521 {
2522 if (!non_stop)
2523 {
2524 /* Check if among the threads that GDB wants actioned, there's
2525 one with a pending status to report. If so, skip actually
2526 resuming/stopping and report the pending event
2527 immediately. */
2528 struct visit_actioned_threads_data data;
2529
2530 data.actions = actions;
2531 data.num_actions = num_actions;
2532 data.callback = handle_pending_status;
2533 if (find_inferior (&all_threads, visit_actioned_threads, &data) != NULL)
2534 return;
2535
2536 enable_async_io ();
2537 }
2538
2539 (*the_target->resume) (actions, num_actions);
2540
2541 if (non_stop)
2542 write_ok (own_buf);
2543 else
2544 {
2545 last_ptid = mywait (minus_one_ptid, &last_status, 0, 1);
2546
2547 if (last_status.kind == TARGET_WAITKIND_NO_RESUMED)
2548 {
2549 /* No proper RSP support for this yet. At least return
2550 error. */
2551 sprintf (own_buf, "E.No unwaited-for children left.");
2552 disable_async_io ();
2553 return;
2554 }
2555
2556 if (last_status.kind != TARGET_WAITKIND_EXITED
2557 && last_status.kind != TARGET_WAITKIND_SIGNALLED
2558 && last_status.kind != TARGET_WAITKIND_NO_RESUMED)
2559 current_thread->last_status = last_status;
2560
2561 /* From the client's perspective, all-stop mode always stops all
2562 threads implicitly (and the target backend has already done
2563 so by now). Tag all threads as "want-stopped", so we don't
2564 resume them implicitly without the client telling us to. */
2565 gdb_wants_all_threads_stopped ();
2566 prepare_resume_reply (own_buf, last_ptid, &last_status);
2567 disable_async_io ();
2568
2569 if (last_status.kind == TARGET_WAITKIND_EXITED
2570 || last_status.kind == TARGET_WAITKIND_SIGNALLED)
2571 mourn_inferior (find_process_pid (ptid_get_pid (last_ptid)));
2572 }
2573 }
2574
2575 /* Attach to a new program. Return 1 if successful, 0 if failure. */
2576 int
2577 handle_v_attach (char *own_buf)
2578 {
2579 int pid;
2580
2581 pid = strtol (own_buf + 8, NULL, 16);
2582 if (pid != 0 && attach_inferior (pid) == 0)
2583 {
2584 /* Don't report shared library events after attaching, even if
2585 some libraries are preloaded. GDB will always poll the
2586 library list. Avoids the "stopped by shared library event"
2587 notice on the GDB side. */
2588 dlls_changed = 0;
2589
2590 if (non_stop)
2591 {
2592 /* In non-stop, we don't send a resume reply. Stop events
2593 will follow up using the normal notification
2594 mechanism. */
2595 write_ok (own_buf);
2596 }
2597 else
2598 prepare_resume_reply (own_buf, last_ptid, &last_status);
2599
2600 return 1;
2601 }
2602 else
2603 {
2604 write_enn (own_buf);
2605 return 0;
2606 }
2607 }
2608
2609 /* Run a new program. Return 1 if successful, 0 if failure. */
2610 static int
2611 handle_v_run (char *own_buf)
2612 {
2613 char *p, *next_p, **new_argv;
2614 int i, new_argc;
2615
2616 new_argc = 0;
2617 for (p = own_buf + strlen ("vRun;"); p && *p; p = strchr (p, ';'))
2618 {
2619 p++;
2620 new_argc++;
2621 }
2622
2623 new_argv = calloc (new_argc + 2, sizeof (char *));
2624 if (new_argv == NULL)
2625 {
2626 write_enn (own_buf);
2627 return 0;
2628 }
2629
2630 i = 0;
2631 for (p = own_buf + strlen ("vRun;"); *p; p = next_p)
2632 {
2633 next_p = strchr (p, ';');
2634 if (next_p == NULL)
2635 next_p = p + strlen (p);
2636
2637 if (i == 0 && p == next_p)
2638 new_argv[i] = NULL;
2639 else
2640 {
2641 /* FIXME: Fail request if out of memory instead of dying. */
2642 new_argv[i] = xmalloc (1 + (next_p - p) / 2);
2643 hex2bin (p, (gdb_byte *) new_argv[i], (next_p - p) / 2);
2644 new_argv[i][(next_p - p) / 2] = '\0';
2645 }
2646
2647 if (*next_p)
2648 next_p++;
2649 i++;
2650 }
2651 new_argv[i] = NULL;
2652
2653 if (new_argv[0] == NULL)
2654 {
2655 /* GDB didn't specify a program to run. Use the program from the
2656 last run with the new argument list. */
2657
2658 if (program_argv == NULL)
2659 {
2660 write_enn (own_buf);
2661 freeargv (new_argv);
2662 return 0;
2663 }
2664
2665 new_argv[0] = strdup (program_argv[0]);
2666 if (new_argv[0] == NULL)
2667 {
2668 write_enn (own_buf);
2669 freeargv (new_argv);
2670 return 0;
2671 }
2672 }
2673
2674 /* Free the old argv and install the new one. */
2675 freeargv (program_argv);
2676 program_argv = new_argv;
2677
2678 start_inferior (program_argv);
2679 if (last_status.kind == TARGET_WAITKIND_STOPPED)
2680 {
2681 prepare_resume_reply (own_buf, last_ptid, &last_status);
2682
2683 /* In non-stop, sending a resume reply doesn't set the general
2684 thread, but GDB assumes a vRun sets it (this is so GDB can
2685 query which is the main thread of the new inferior. */
2686 if (non_stop)
2687 general_thread = last_ptid;
2688
2689 return 1;
2690 }
2691 else
2692 {
2693 write_enn (own_buf);
2694 return 0;
2695 }
2696 }
2697
2698 /* Kill process. Return 1 if successful, 0 if failure. */
2699 int
2700 handle_v_kill (char *own_buf)
2701 {
2702 int pid;
2703 char *p = &own_buf[6];
2704 if (multi_process)
2705 pid = strtol (p, NULL, 16);
2706 else
2707 pid = signal_pid;
2708 if (pid != 0 && kill_inferior (pid) == 0)
2709 {
2710 last_status.kind = TARGET_WAITKIND_SIGNALLED;
2711 last_status.value.sig = GDB_SIGNAL_KILL;
2712 last_ptid = pid_to_ptid (pid);
2713 discard_queued_stop_replies (pid);
2714 write_ok (own_buf);
2715 return 1;
2716 }
2717 else
2718 {
2719 write_enn (own_buf);
2720 return 0;
2721 }
2722 }
2723
2724 /* Handle all of the extended 'v' packets. */
2725 void
2726 handle_v_requests (char *own_buf, int packet_len, int *new_packet_len)
2727 {
2728 if (!disable_packet_vCont)
2729 {
2730 if (startswith (own_buf, "vCont;"))
2731 {
2732 require_running (own_buf);
2733 handle_v_cont (own_buf);
2734 return;
2735 }
2736
2737 if (startswith (own_buf, "vCont?"))
2738 {
2739 strcpy (own_buf, "vCont;c;C;s;S;t");
2740 if (target_supports_range_stepping ())
2741 {
2742 own_buf = own_buf + strlen (own_buf);
2743 strcpy (own_buf, ";r");
2744 }
2745 return;
2746 }
2747 }
2748
2749 if (startswith (own_buf, "vFile:")
2750 && handle_vFile (own_buf, packet_len, new_packet_len))
2751 return;
2752
2753 if (startswith (own_buf, "vAttach;"))
2754 {
2755 if ((!extended_protocol || !multi_process) && target_running ())
2756 {
2757 fprintf (stderr, "Already debugging a process\n");
2758 write_enn (own_buf);
2759 return;
2760 }
2761 handle_v_attach (own_buf);
2762 return;
2763 }
2764
2765 if (startswith (own_buf, "vRun;"))
2766 {
2767 if ((!extended_protocol || !multi_process) && target_running ())
2768 {
2769 fprintf (stderr, "Already debugging a process\n");
2770 write_enn (own_buf);
2771 return;
2772 }
2773 handle_v_run (own_buf);
2774 return;
2775 }
2776
2777 if (startswith (own_buf, "vKill;"))
2778 {
2779 if (!target_running ())
2780 {
2781 fprintf (stderr, "No process to kill\n");
2782 write_enn (own_buf);
2783 return;
2784 }
2785 handle_v_kill (own_buf);
2786 return;
2787 }
2788
2789 if (handle_notif_ack (own_buf, packet_len))
2790 return;
2791
2792 /* Otherwise we didn't know what packet it was. Say we didn't
2793 understand it. */
2794 own_buf[0] = 0;
2795 return;
2796 }
2797
2798 /* Resume thread and wait for another event. In non-stop mode,
2799 don't really wait here, but return immediatelly to the event
2800 loop. */
2801 static void
2802 myresume (char *own_buf, int step, int sig)
2803 {
2804 struct thread_resume resume_info[2];
2805 int n = 0;
2806 int valid_cont_thread;
2807
2808 set_desired_thread (0);
2809
2810 valid_cont_thread = (!ptid_equal (cont_thread, null_ptid)
2811 && !ptid_equal (cont_thread, minus_one_ptid));
2812
2813 if (step || sig || valid_cont_thread)
2814 {
2815 resume_info[0].thread = current_ptid;
2816 if (step)
2817 resume_info[0].kind = resume_step;
2818 else
2819 resume_info[0].kind = resume_continue;
2820 resume_info[0].sig = sig;
2821 n++;
2822 }
2823
2824 if (!valid_cont_thread)
2825 {
2826 resume_info[n].thread = minus_one_ptid;
2827 resume_info[n].kind = resume_continue;
2828 resume_info[n].sig = 0;
2829 n++;
2830 }
2831
2832 resume (resume_info, n);
2833 }
2834
2835 /* Callback for for_each_inferior. Make a new stop reply for each
2836 stopped thread. */
2837
2838 static int
2839 queue_stop_reply_callback (struct inferior_list_entry *entry, void *arg)
2840 {
2841 struct thread_info *thread = (struct thread_info *) entry;
2842
2843 /* For now, assume targets that don't have this callback also don't
2844 manage the thread's last_status field. */
2845 if (the_target->thread_stopped == NULL)
2846 {
2847 struct vstop_notif *new_notif = xmalloc (sizeof (*new_notif));
2848
2849 new_notif->ptid = entry->id;
2850 new_notif->status = thread->last_status;
2851 /* Pass the last stop reply back to GDB, but don't notify
2852 yet. */
2853 notif_event_enque (&notif_stop,
2854 (struct notif_event *) new_notif);
2855 }
2856 else
2857 {
2858 if (thread_stopped (thread))
2859 {
2860 if (debug_threads)
2861 {
2862 char *status_string
2863 = target_waitstatus_to_string (&thread->last_status);
2864
2865 debug_printf ("Reporting thread %s as already stopped with %s\n",
2866 target_pid_to_str (entry->id),
2867 status_string);
2868
2869 xfree (status_string);
2870 }
2871
2872 gdb_assert (thread->last_status.kind != TARGET_WAITKIND_IGNORE);
2873
2874 /* Pass the last stop reply back to GDB, but don't notify
2875 yet. */
2876 queue_stop_reply (entry->id, &thread->last_status);
2877 }
2878 }
2879
2880 return 0;
2881 }
2882
2883 /* Set this inferior threads's state as "want-stopped". We won't
2884 resume this thread until the client gives us another action for
2885 it. */
2886
2887 static void
2888 gdb_wants_thread_stopped (struct inferior_list_entry *entry)
2889 {
2890 struct thread_info *thread = (struct thread_info *) entry;
2891
2892 thread->last_resume_kind = resume_stop;
2893
2894 if (thread->last_status.kind == TARGET_WAITKIND_IGNORE)
2895 {
2896 /* Most threads are stopped implicitly (all-stop); tag that with
2897 signal 0. */
2898 thread->last_status.kind = TARGET_WAITKIND_STOPPED;
2899 thread->last_status.value.sig = GDB_SIGNAL_0;
2900 }
2901 }
2902
2903 /* Set all threads' states as "want-stopped". */
2904
2905 static void
2906 gdb_wants_all_threads_stopped (void)
2907 {
2908 for_each_inferior (&all_threads, gdb_wants_thread_stopped);
2909 }
2910
2911 /* Clear the gdb_detached flag of every process. */
2912
2913 static void
2914 gdb_reattached_process (struct inferior_list_entry *entry)
2915 {
2916 struct process_info *process = (struct process_info *) entry;
2917
2918 process->gdb_detached = 0;
2919 }
2920
2921 /* Callback for for_each_inferior. Clear the thread's pending status
2922 flag. */
2923
2924 static void
2925 clear_pending_status_callback (struct inferior_list_entry *entry)
2926 {
2927 struct thread_info *thread = (struct thread_info *) entry;
2928
2929 thread->status_pending_p = 0;
2930 }
2931
2932 /* Callback for for_each_inferior. If the thread is stopped with an
2933 interesting event, mark it as having a pending event. */
2934
2935 static void
2936 set_pending_status_callback (struct inferior_list_entry *entry)
2937 {
2938 struct thread_info *thread = (struct thread_info *) entry;
2939
2940 if (thread->last_status.kind != TARGET_WAITKIND_STOPPED
2941 || (thread->last_status.value.sig != GDB_SIGNAL_0
2942 /* A breakpoint, watchpoint or finished step from a previous
2943 GDB run isn't considered interesting for a new GDB run.
2944 If we left those pending, the new GDB could consider them
2945 random SIGTRAPs. This leaves out real async traps. We'd
2946 have to peek into the (target-specific) siginfo to
2947 distinguish those. */
2948 && thread->last_status.value.sig != GDB_SIGNAL_TRAP))
2949 thread->status_pending_p = 1;
2950 }
2951
2952 /* Callback for find_inferior. Return true if ENTRY (a thread) has a
2953 pending status to report to GDB. */
2954
2955 static int
2956 find_status_pending_thread_callback (struct inferior_list_entry *entry, void *data)
2957 {
2958 struct thread_info *thread = (struct thread_info *) entry;
2959
2960 return thread->status_pending_p;
2961 }
2962
2963 /* Status handler for the '?' packet. */
2964
2965 static void
2966 handle_status (char *own_buf)
2967 {
2968 /* GDB is connected, don't forward events to the target anymore. */
2969 for_each_inferior (&all_processes, gdb_reattached_process);
2970
2971 /* In non-stop mode, we must send a stop reply for each stopped
2972 thread. In all-stop mode, just send one for the first stopped
2973 thread we find. */
2974
2975 if (non_stop)
2976 {
2977 find_inferior (&all_threads, queue_stop_reply_callback, NULL);
2978
2979 /* The first is sent immediatly. OK is sent if there is no
2980 stopped thread, which is the same handling of the vStopped
2981 packet (by design). */
2982 notif_write_event (&notif_stop, own_buf);
2983 }
2984 else
2985 {
2986 struct inferior_list_entry *thread = NULL;
2987
2988 pause_all (0);
2989 stabilize_threads ();
2990 gdb_wants_all_threads_stopped ();
2991
2992 /* We can only report one status, but we might be coming out of
2993 non-stop -- if more than one thread is stopped with
2994 interesting events, leave events for the threads we're not
2995 reporting now pending. They'll be reported the next time the
2996 threads are resumed. Start by marking all interesting events
2997 as pending. */
2998 for_each_inferior (&all_threads, set_pending_status_callback);
2999
3000 /* Prefer the last thread that reported an event to GDB (even if
3001 that was a GDB_SIGNAL_TRAP). */
3002 if (last_status.kind != TARGET_WAITKIND_IGNORE
3003 && last_status.kind != TARGET_WAITKIND_EXITED
3004 && last_status.kind != TARGET_WAITKIND_SIGNALLED)
3005 thread = find_inferior_id (&all_threads, last_ptid);
3006
3007 /* If the last event thread is not found for some reason, look
3008 for some other thread that might have an event to report. */
3009 if (thread == NULL)
3010 thread = find_inferior (&all_threads,
3011 find_status_pending_thread_callback, NULL);
3012
3013 /* If we're still out of luck, simply pick the first thread in
3014 the thread list. */
3015 if (thread == NULL)
3016 thread = get_first_inferior (&all_threads);
3017
3018 if (thread != NULL)
3019 {
3020 struct thread_info *tp = (struct thread_info *) thread;
3021
3022 /* We're reporting this event, so it's no longer
3023 pending. */
3024 tp->status_pending_p = 0;
3025
3026 /* GDB assumes the current thread is the thread we're
3027 reporting the status for. */
3028 general_thread = thread->id;
3029 set_desired_thread (1);
3030
3031 gdb_assert (tp->last_status.kind != TARGET_WAITKIND_IGNORE);
3032 prepare_resume_reply (own_buf, tp->entry.id, &tp->last_status);
3033 }
3034 else
3035 strcpy (own_buf, "W00");
3036 }
3037 }
3038
3039 static void
3040 gdbserver_version (void)
3041 {
3042 printf ("GNU gdbserver %s%s\n"
3043 "Copyright (C) 2015 Free Software Foundation, Inc.\n"
3044 "gdbserver is free software, covered by the "
3045 "GNU General Public License.\n"
3046 "This gdbserver was configured as \"%s\"\n",
3047 PKGVERSION, version, host_name);
3048 }
3049
3050 static void
3051 gdbserver_usage (FILE *stream)
3052 {
3053 fprintf (stream, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3054 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3055 "\tgdbserver [OPTIONS] --multi COMM\n"
3056 "\n"
3057 "COMM may either be a tty device (for serial debugging),\n"
3058 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3059 "stdin/stdout of gdbserver.\n"
3060 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3061 "PID is the process ID to attach to, when --attach is specified.\n"
3062 "\n"
3063 "Operating modes:\n"
3064 "\n"
3065 " --attach Attach to running process PID.\n"
3066 " --multi Start server without a specific program, and\n"
3067 " only quit when explicitly commanded.\n"
3068 " --once Exit after the first connection has closed.\n"
3069 " --help Print this message and then exit.\n"
3070 " --version Display version information and exit.\n"
3071 "\n"
3072 "Other options:\n"
3073 "\n"
3074 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3075 " --disable-randomization\n"
3076 " Run PROG with address space randomization disabled.\n"
3077 " --no-disable-randomization\n"
3078 " Don't disable address space randomization when\n"
3079 " starting PROG.\n"
3080 "\n"
3081 "Debug options:\n"
3082 "\n"
3083 " --debug Enable general debugging output.\n"
3084 " --debug-format=opt1[,opt2,...]\n"
3085 " Specify extra content in debugging output.\n"
3086 " Options:\n"
3087 " all\n"
3088 " none\n"
3089 " timestamp\n"
3090 " --remote-debug Enable remote protocol debugging output.\n"
3091 " --disable-packet=opt1[,opt2,...]\n"
3092 " Disable support for RSP packets or features.\n"
3093 " Options:\n"
3094 " vCont, Tthread, qC, qfThreadInfo and \n"
3095 " threads (disable all threading packets).\n"
3096 "\n"
3097 "For more information, consult the GDB manual (available as on-line \n"
3098 "info or a printed manual).\n");
3099 if (REPORT_BUGS_TO[0] && stream == stdout)
3100 fprintf (stream, "Report bugs to \"%s\".\n", REPORT_BUGS_TO);
3101 }
3102
3103 static void
3104 gdbserver_show_disableable (FILE *stream)
3105 {
3106 fprintf (stream, "Disableable packets:\n"
3107 " vCont \tAll vCont packets\n"
3108 " qC \tQuerying the current thread\n"
3109 " qfThreadInfo\tThread listing\n"
3110 " Tthread \tPassing the thread specifier in the "
3111 "T stop reply packet\n"
3112 " threads \tAll of the above\n");
3113 }
3114
3115
3116 #undef require_running
3117 #define require_running(BUF) \
3118 if (!target_running ()) \
3119 { \
3120 write_enn (BUF); \
3121 break; \
3122 }
3123
3124 static int
3125 first_thread_of (struct inferior_list_entry *entry, void *args)
3126 {
3127 int pid = * (int *) args;
3128
3129 if (ptid_get_pid (entry->id) == pid)
3130 return 1;
3131
3132 return 0;
3133 }
3134
3135 static void
3136 kill_inferior_callback (struct inferior_list_entry *entry)
3137 {
3138 struct process_info *process = (struct process_info *) entry;
3139 int pid = ptid_get_pid (process->entry.id);
3140
3141 kill_inferior (pid);
3142 discard_queued_stop_replies (pid);
3143 }
3144
3145 /* Callback for for_each_inferior to detach or kill the inferior,
3146 depending on whether we attached to it or not.
3147 We inform the user whether we're detaching or killing the process
3148 as this is only called when gdbserver is about to exit. */
3149
3150 static void
3151 detach_or_kill_inferior_callback (struct inferior_list_entry *entry)
3152 {
3153 struct process_info *process = (struct process_info *) entry;
3154 int pid = ptid_get_pid (process->entry.id);
3155
3156 if (process->attached)
3157 detach_inferior (pid);
3158 else
3159 kill_inferior (pid);
3160
3161 discard_queued_stop_replies (pid);
3162 }
3163
3164 /* for_each_inferior callback for detach_or_kill_for_exit to print
3165 the pids of started inferiors. */
3166
3167 static void
3168 print_started_pid (struct inferior_list_entry *entry)
3169 {
3170 struct process_info *process = (struct process_info *) entry;
3171
3172 if (! process->attached)
3173 {
3174 int pid = ptid_get_pid (process->entry.id);
3175 fprintf (stderr, " %d", pid);
3176 }
3177 }
3178
3179 /* for_each_inferior callback for detach_or_kill_for_exit to print
3180 the pids of attached inferiors. */
3181
3182 static void
3183 print_attached_pid (struct inferior_list_entry *entry)
3184 {
3185 struct process_info *process = (struct process_info *) entry;
3186
3187 if (process->attached)
3188 {
3189 int pid = ptid_get_pid (process->entry.id);
3190 fprintf (stderr, " %d", pid);
3191 }
3192 }
3193
3194 /* Call this when exiting gdbserver with possible inferiors that need
3195 to be killed or detached from. */
3196
3197 static void
3198 detach_or_kill_for_exit (void)
3199 {
3200 /* First print a list of the inferiors we will be killing/detaching.
3201 This is to assist the user, for example, in case the inferior unexpectedly
3202 dies after we exit: did we screw up or did the inferior exit on its own?
3203 Having this info will save some head-scratching. */
3204
3205 if (have_started_inferiors_p ())
3206 {
3207 fprintf (stderr, "Killing process(es):");
3208 for_each_inferior (&all_processes, print_started_pid);
3209 fprintf (stderr, "\n");
3210 }
3211 if (have_attached_inferiors_p ())
3212 {
3213 fprintf (stderr, "Detaching process(es):");
3214 for_each_inferior (&all_processes, print_attached_pid);
3215 fprintf (stderr, "\n");
3216 }
3217
3218 /* Now we can kill or detach the inferiors. */
3219
3220 for_each_inferior (&all_processes, detach_or_kill_inferior_callback);
3221 }
3222
3223 /* Value that will be passed to exit(3) when gdbserver exits. */
3224 static int exit_code;
3225
3226 /* Cleanup version of detach_or_kill_for_exit. */
3227
3228 static void
3229 detach_or_kill_for_exit_cleanup (void *ignore)
3230 {
3231
3232 TRY
3233 {
3234 detach_or_kill_for_exit ();
3235 }
3236
3237 CATCH (exception, RETURN_MASK_ALL)
3238 {
3239 fflush (stdout);
3240 fprintf (stderr, "Detach or kill failed: %s\n", exception.message);
3241 exit_code = 1;
3242 }
3243 END_CATCH
3244 }
3245
3246 /* Main function. This is called by the real "main" function,
3247 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
3248
3249 static void ATTRIBUTE_NORETURN
3250 captured_main (int argc, char *argv[])
3251 {
3252 int bad_attach;
3253 int pid;
3254 char *arg_end, *port;
3255 char **next_arg = &argv[1];
3256 volatile int multi_mode = 0;
3257 volatile int attach = 0;
3258 int was_running;
3259
3260 while (*next_arg != NULL && **next_arg == '-')
3261 {
3262 if (strcmp (*next_arg, "--version") == 0)
3263 {
3264 gdbserver_version ();
3265 exit (0);
3266 }
3267 else if (strcmp (*next_arg, "--help") == 0)
3268 {
3269 gdbserver_usage (stdout);
3270 exit (0);
3271 }
3272 else if (strcmp (*next_arg, "--attach") == 0)
3273 attach = 1;
3274 else if (strcmp (*next_arg, "--multi") == 0)
3275 multi_mode = 1;
3276 else if (strcmp (*next_arg, "--wrapper") == 0)
3277 {
3278 next_arg++;
3279
3280 wrapper_argv = next_arg;
3281 while (*next_arg != NULL && strcmp (*next_arg, "--") != 0)
3282 next_arg++;
3283
3284 if (next_arg == wrapper_argv || *next_arg == NULL)
3285 {
3286 gdbserver_usage (stderr);
3287 exit (1);
3288 }
3289
3290 /* Consume the "--". */
3291 *next_arg = NULL;
3292 }
3293 else if (strcmp (*next_arg, "--debug") == 0)
3294 debug_threads = 1;
3295 else if (startswith (*next_arg, "--debug-format="))
3296 {
3297 char *error_msg
3298 = parse_debug_format_options ((*next_arg)
3299 + sizeof ("--debug-format=") - 1, 0);
3300
3301 if (error_msg != NULL)
3302 {
3303 fprintf (stderr, "%s", error_msg);
3304 exit (1);
3305 }
3306 }
3307 else if (strcmp (*next_arg, "--remote-debug") == 0)
3308 remote_debug = 1;
3309 else if (strcmp (*next_arg, "--disable-packet") == 0)
3310 {
3311 gdbserver_show_disableable (stdout);
3312 exit (0);
3313 }
3314 else if (startswith (*next_arg, "--disable-packet="))
3315 {
3316 char *packets, *tok;
3317
3318 packets = *next_arg += sizeof ("--disable-packet=") - 1;
3319 for (tok = strtok (packets, ",");
3320 tok != NULL;
3321 tok = strtok (NULL, ","))
3322 {
3323 if (strcmp ("vCont", tok) == 0)
3324 disable_packet_vCont = 1;
3325 else if (strcmp ("Tthread", tok) == 0)
3326 disable_packet_Tthread = 1;
3327 else if (strcmp ("qC", tok) == 0)
3328 disable_packet_qC = 1;
3329 else if (strcmp ("qfThreadInfo", tok) == 0)
3330 disable_packet_qfThreadInfo = 1;
3331 else if (strcmp ("threads", tok) == 0)
3332 {
3333 disable_packet_vCont = 1;
3334 disable_packet_Tthread = 1;
3335 disable_packet_qC = 1;
3336 disable_packet_qfThreadInfo = 1;
3337 }
3338 else
3339 {
3340 fprintf (stderr, "Don't know how to disable \"%s\".\n\n",
3341 tok);
3342 gdbserver_show_disableable (stderr);
3343 exit (1);
3344 }
3345 }
3346 }
3347 else if (strcmp (*next_arg, "-") == 0)
3348 {
3349 /* "-" specifies a stdio connection and is a form of port
3350 specification. */
3351 *next_arg = STDIO_CONNECTION_NAME;
3352 break;
3353 }
3354 else if (strcmp (*next_arg, "--disable-randomization") == 0)
3355 disable_randomization = 1;
3356 else if (strcmp (*next_arg, "--no-disable-randomization") == 0)
3357 disable_randomization = 0;
3358 else if (strcmp (*next_arg, "--once") == 0)
3359 run_once = 1;
3360 else
3361 {
3362 fprintf (stderr, "Unknown argument: %s\n", *next_arg);
3363 exit (1);
3364 }
3365
3366 next_arg++;
3367 continue;
3368 }
3369
3370 port = *next_arg;
3371 next_arg++;
3372 if (port == NULL || (!attach && !multi_mode && *next_arg == NULL))
3373 {
3374 gdbserver_usage (stderr);
3375 exit (1);
3376 }
3377
3378 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
3379 opened by remote_prepare. */
3380 notice_open_fds ();
3381
3382 /* We need to know whether the remote connection is stdio before
3383 starting the inferior. Inferiors created in this scenario have
3384 stdin,stdout redirected. So do this here before we call
3385 start_inferior. */
3386 remote_prepare (port);
3387
3388 bad_attach = 0;
3389 pid = 0;
3390
3391 /* --attach used to come after PORT, so allow it there for
3392 compatibility. */
3393 if (*next_arg != NULL && strcmp (*next_arg, "--attach") == 0)
3394 {
3395 attach = 1;
3396 next_arg++;
3397 }
3398
3399 if (attach
3400 && (*next_arg == NULL
3401 || (*next_arg)[0] == '\0'
3402 || (pid = strtoul (*next_arg, &arg_end, 0)) == 0
3403 || *arg_end != '\0'
3404 || next_arg[1] != NULL))
3405 bad_attach = 1;
3406
3407 if (bad_attach)
3408 {
3409 gdbserver_usage (stderr);
3410 exit (1);
3411 }
3412
3413 initialize_async_io ();
3414 initialize_low ();
3415 initialize_event_loop ();
3416 if (target_supports_tracepoints ())
3417 initialize_tracepoint ();
3418
3419 own_buf = xmalloc (PBUFSIZ + 1);
3420 mem_buf = xmalloc (PBUFSIZ);
3421
3422 if (pid == 0 && *next_arg != NULL)
3423 {
3424 int i, n;
3425
3426 n = argc - (next_arg - argv);
3427 program_argv = xmalloc (sizeof (char *) * (n + 1));
3428 for (i = 0; i < n; i++)
3429 program_argv[i] = xstrdup (next_arg[i]);
3430 program_argv[i] = NULL;
3431
3432 /* Wait till we are at first instruction in program. */
3433 start_inferior (program_argv);
3434
3435 /* We are now (hopefully) stopped at the first instruction of
3436 the target process. This assumes that the target process was
3437 successfully created. */
3438 }
3439 else if (pid != 0)
3440 {
3441 if (attach_inferior (pid) == -1)
3442 error ("Attaching not supported on this target");
3443
3444 /* Otherwise succeeded. */
3445 }
3446 else
3447 {
3448 last_status.kind = TARGET_WAITKIND_EXITED;
3449 last_status.value.integer = 0;
3450 last_ptid = minus_one_ptid;
3451 }
3452 make_cleanup (detach_or_kill_for_exit_cleanup, NULL);
3453
3454 initialize_notif ();
3455
3456 /* Don't report shared library events on the initial connection,
3457 even if some libraries are preloaded. Avoids the "stopped by
3458 shared library event" notice on gdb side. */
3459 dlls_changed = 0;
3460
3461 if (last_status.kind == TARGET_WAITKIND_EXITED
3462 || last_status.kind == TARGET_WAITKIND_SIGNALLED)
3463 was_running = 0;
3464 else
3465 was_running = 1;
3466
3467 if (!was_running && !multi_mode)
3468 error ("No program to debug");
3469
3470 while (1)
3471 {
3472
3473 noack_mode = 0;
3474 multi_process = 0;
3475 /* Be sure we're out of tfind mode. */
3476 current_traceframe = -1;
3477 cont_thread = null_ptid;
3478 swbreak_feature = 0;
3479 hwbreak_feature = 0;
3480
3481 remote_open (port);
3482
3483 TRY
3484 {
3485 /* Wait for events. This will return when all event sources
3486 are removed from the event loop. */
3487 start_event_loop ();
3488
3489 /* If an exit was requested (using the "monitor exit"
3490 command), terminate now. The only other way to get
3491 here is for getpkt to fail; close the connection
3492 and reopen it at the top of the loop. */
3493
3494 if (exit_requested || run_once)
3495 throw_quit ("Quit");
3496
3497 fprintf (stderr,
3498 "Remote side has terminated connection. "
3499 "GDBserver will reopen the connection.\n");
3500
3501 /* Get rid of any pending statuses. An eventual reconnection
3502 (by the same GDB instance or another) will refresh all its
3503 state from scratch. */
3504 discard_queued_stop_replies (-1);
3505 for_each_inferior (&all_threads,
3506 clear_pending_status_callback);
3507
3508 if (tracing)
3509 {
3510 if (disconnected_tracing)
3511 {
3512 /* Try to enable non-stop/async mode, so we we can
3513 both wait for an async socket accept, and handle
3514 async target events simultaneously. There's also
3515 no point either in having the target always stop
3516 all threads, when we're going to pass signals
3517 down without informing GDB. */
3518 if (!non_stop)
3519 {
3520 if (start_non_stop (1))
3521 non_stop = 1;
3522
3523 /* Detaching implicitly resumes all threads;
3524 simply disconnecting does not. */
3525 }
3526 }
3527 else
3528 {
3529 fprintf (stderr,
3530 "Disconnected tracing disabled; "
3531 "stopping trace run.\n");
3532 stop_tracing ();
3533 }
3534 }
3535 }
3536 CATCH (exception, RETURN_MASK_ERROR)
3537 {
3538 if (response_needed)
3539 {
3540 write_enn (own_buf);
3541 putpkt (own_buf);
3542 }
3543 }
3544 END_CATCH
3545 }
3546 }
3547
3548 /* Main function. */
3549
3550 int
3551 main (int argc, char *argv[])
3552 {
3553
3554 TRY
3555 {
3556 captured_main (argc, argv);
3557 }
3558 CATCH (exception, RETURN_MASK_ALL)
3559 {
3560 if (exception.reason == RETURN_ERROR)
3561 {
3562 fflush (stdout);
3563 fprintf (stderr, "%s\n", exception.message);
3564 fprintf (stderr, "Exiting\n");
3565 exit_code = 1;
3566 }
3567
3568 exit (exit_code);
3569 }
3570 END_CATCH
3571
3572 gdb_assert_not_reached ("captured_main should never return");
3573 }
3574
3575 /* Skip PACKET until the next semi-colon (or end of string). */
3576
3577 static void
3578 skip_to_semicolon (char **packet)
3579 {
3580 while (**packet != '\0' && **packet != ';')
3581 (*packet)++;
3582 }
3583
3584 /* Process options coming from Z packets for a breakpoint. PACKET is
3585 the packet buffer. *PACKET is updated to point to the first char
3586 after the last processed option. */
3587
3588 static void
3589 process_point_options (struct breakpoint *bp, char **packet)
3590 {
3591 char *dataptr = *packet;
3592 int persist;
3593
3594 /* Check if data has the correct format. */
3595 if (*dataptr != ';')
3596 return;
3597
3598 dataptr++;
3599
3600 while (*dataptr)
3601 {
3602 if (*dataptr == ';')
3603 ++dataptr;
3604
3605 if (*dataptr == 'X')
3606 {
3607 /* Conditional expression. */
3608 if (debug_threads)
3609 debug_printf ("Found breakpoint condition.\n");
3610 if (!add_breakpoint_condition (bp, &dataptr))
3611 skip_to_semicolon (&dataptr);
3612 }
3613 else if (startswith (dataptr, "cmds:"))
3614 {
3615 dataptr += strlen ("cmds:");
3616 if (debug_threads)
3617 debug_printf ("Found breakpoint commands %s.\n", dataptr);
3618 persist = (*dataptr == '1');
3619 dataptr += 2;
3620 if (add_breakpoint_commands (bp, &dataptr, persist))
3621 skip_to_semicolon (&dataptr);
3622 }
3623 else
3624 {
3625 fprintf (stderr, "Unknown token %c, ignoring.\n",
3626 *dataptr);
3627 /* Skip tokens until we find one that we recognize. */
3628 skip_to_semicolon (&dataptr);
3629 }
3630 }
3631 *packet = dataptr;
3632 }
3633
3634 /* Event loop callback that handles a serial event. The first byte in
3635 the serial buffer gets us here. We expect characters to arrive at
3636 a brisk pace, so we read the rest of the packet with a blocking
3637 getpkt call. */
3638
3639 static int
3640 process_serial_event (void)
3641 {
3642 char ch;
3643 int i = 0;
3644 int signal;
3645 unsigned int len;
3646 int res;
3647 CORE_ADDR mem_addr;
3648 int pid;
3649 unsigned char sig;
3650 int packet_len;
3651 int new_packet_len = -1;
3652
3653 /* Used to decide when gdbserver should exit in
3654 multi-mode/remote. */
3655 static int have_ran = 0;
3656
3657 if (!have_ran)
3658 have_ran = target_running ();
3659
3660 disable_async_io ();
3661
3662 response_needed = 0;
3663 packet_len = getpkt (own_buf);
3664 if (packet_len <= 0)
3665 {
3666 remote_close ();
3667 /* Force an event loop break. */
3668 return -1;
3669 }
3670 response_needed = 1;
3671
3672 i = 0;
3673 ch = own_buf[i++];
3674 switch (ch)
3675 {
3676 case 'q':
3677 handle_query (own_buf, packet_len, &new_packet_len);
3678 break;
3679 case 'Q':
3680 handle_general_set (own_buf);
3681 break;
3682 case 'D':
3683 require_running (own_buf);
3684
3685 if (multi_process)
3686 {
3687 i++; /* skip ';' */
3688 pid = strtol (&own_buf[i], NULL, 16);
3689 }
3690 else
3691 pid = ptid_get_pid (current_ptid);
3692
3693 if ((tracing && disconnected_tracing) || any_persistent_commands ())
3694 {
3695 struct thread_resume resume_info;
3696 struct process_info *process = find_process_pid (pid);
3697
3698 if (process == NULL)
3699 {
3700 write_enn (own_buf);
3701 break;
3702 }
3703
3704 if (tracing && disconnected_tracing)
3705 fprintf (stderr,
3706 "Disconnected tracing in effect, "
3707 "leaving gdbserver attached to the process\n");
3708
3709 if (any_persistent_commands ())
3710 fprintf (stderr,
3711 "Persistent commands are present, "
3712 "leaving gdbserver attached to the process\n");
3713
3714 /* Make sure we're in non-stop/async mode, so we we can both
3715 wait for an async socket accept, and handle async target
3716 events simultaneously. There's also no point either in
3717 having the target stop all threads, when we're going to
3718 pass signals down without informing GDB. */
3719 if (!non_stop)
3720 {
3721 if (debug_threads)
3722 debug_printf ("Forcing non-stop mode\n");
3723
3724 non_stop = 1;
3725 start_non_stop (1);
3726 }
3727
3728 process->gdb_detached = 1;
3729
3730 /* Detaching implicitly resumes all threads. */
3731 resume_info.thread = minus_one_ptid;
3732 resume_info.kind = resume_continue;
3733 resume_info.sig = 0;
3734 (*the_target->resume) (&resume_info, 1);
3735
3736 write_ok (own_buf);
3737 break; /* from switch/case */
3738 }
3739
3740 fprintf (stderr, "Detaching from process %d\n", pid);
3741 stop_tracing ();
3742 if (detach_inferior (pid) != 0)
3743 write_enn (own_buf);
3744 else
3745 {
3746 discard_queued_stop_replies (pid);
3747 write_ok (own_buf);
3748
3749 if (extended_protocol)
3750 {
3751 /* Treat this like a normal program exit. */
3752 last_status.kind = TARGET_WAITKIND_EXITED;
3753 last_status.value.integer = 0;
3754 last_ptid = pid_to_ptid (pid);
3755
3756 current_thread = NULL;
3757 }
3758 else
3759 {
3760 putpkt (own_buf);
3761 remote_close ();
3762
3763 /* If we are attached, then we can exit. Otherwise, we
3764 need to hang around doing nothing, until the child is
3765 gone. */
3766 join_inferior (pid);
3767 exit (0);
3768 }
3769 }
3770 break;
3771 case '!':
3772 extended_protocol = 1;
3773 write_ok (own_buf);
3774 break;
3775 case '?':
3776 handle_status (own_buf);
3777 break;
3778 case 'H':
3779 if (own_buf[1] == 'c' || own_buf[1] == 'g' || own_buf[1] == 's')
3780 {
3781 ptid_t gdb_id, thread_id;
3782 int pid;
3783
3784 require_running (own_buf);
3785
3786 gdb_id = read_ptid (&own_buf[2], NULL);
3787
3788 pid = ptid_get_pid (gdb_id);
3789
3790 if (ptid_equal (gdb_id, null_ptid)
3791 || ptid_equal (gdb_id, minus_one_ptid))
3792 thread_id = null_ptid;
3793 else if (pid != 0
3794 && ptid_equal (pid_to_ptid (pid),
3795 gdb_id))
3796 {
3797 struct thread_info *thread =
3798 (struct thread_info *) find_inferior (&all_threads,
3799 first_thread_of,
3800 &pid);
3801 if (!thread)
3802 {
3803 write_enn (own_buf);
3804 break;
3805 }
3806
3807 thread_id = thread->entry.id;
3808 }
3809 else
3810 {
3811 thread_id = gdb_id_to_thread_id (gdb_id);
3812 if (ptid_equal (thread_id, null_ptid))
3813 {
3814 write_enn (own_buf);
3815 break;
3816 }
3817 }
3818
3819 if (own_buf[1] == 'g')
3820 {
3821 if (ptid_equal (thread_id, null_ptid))
3822 {
3823 /* GDB is telling us to choose any thread. Check if
3824 the currently selected thread is still valid. If
3825 it is not, select the first available. */
3826 struct thread_info *thread =
3827 (struct thread_info *) find_inferior_id (&all_threads,
3828 general_thread);
3829 if (thread == NULL)
3830 {
3831 thread = get_first_thread ();
3832 thread_id = thread->entry.id;
3833 }
3834 }
3835
3836 general_thread = thread_id;
3837 set_desired_thread (1);
3838 }
3839 else if (own_buf[1] == 'c')
3840 cont_thread = thread_id;
3841
3842 write_ok (own_buf);
3843 }
3844 else
3845 {
3846 /* Silently ignore it so that gdb can extend the protocol
3847 without compatibility headaches. */
3848 own_buf[0] = '\0';
3849 }
3850 break;
3851 case 'g':
3852 require_running (own_buf);
3853 if (current_traceframe >= 0)
3854 {
3855 struct regcache *regcache
3856 = new_register_cache (current_target_desc ());
3857
3858 if (fetch_traceframe_registers (current_traceframe,
3859 regcache, -1) == 0)
3860 registers_to_string (regcache, own_buf);
3861 else
3862 write_enn (own_buf);
3863 free_register_cache (regcache);
3864 }
3865 else
3866 {
3867 struct regcache *regcache;
3868
3869 set_desired_thread (1);
3870 regcache = get_thread_regcache (current_thread, 1);
3871 registers_to_string (regcache, own_buf);
3872 }
3873 break;
3874 case 'G':
3875 require_running (own_buf);
3876 if (current_traceframe >= 0)
3877 write_enn (own_buf);
3878 else
3879 {
3880 struct regcache *regcache;
3881
3882 set_desired_thread (1);
3883 regcache = get_thread_regcache (current_thread, 1);
3884 registers_from_string (regcache, &own_buf[1]);
3885 write_ok (own_buf);
3886 }
3887 break;
3888 case 'm':
3889 require_running (own_buf);
3890 decode_m_packet (&own_buf[1], &mem_addr, &len);
3891 res = gdb_read_memory (mem_addr, mem_buf, len);
3892 if (res < 0)
3893 write_enn (own_buf);
3894 else
3895 bin2hex (mem_buf, own_buf, res);
3896 break;
3897 case 'M':
3898 require_running (own_buf);
3899 decode_M_packet (&own_buf[1], &mem_addr, &len, &mem_buf);
3900 if (gdb_write_memory (mem_addr, mem_buf, len) == 0)
3901 write_ok (own_buf);
3902 else
3903 write_enn (own_buf);
3904 break;
3905 case 'X':
3906 require_running (own_buf);
3907 if (decode_X_packet (&own_buf[1], packet_len - 1,
3908 &mem_addr, &len, &mem_buf) < 0
3909 || gdb_write_memory (mem_addr, mem_buf, len) != 0)
3910 write_enn (own_buf);
3911 else
3912 write_ok (own_buf);
3913 break;
3914 case 'C':
3915 require_running (own_buf);
3916 hex2bin (own_buf + 1, &sig, 1);
3917 if (gdb_signal_to_host_p (sig))
3918 signal = gdb_signal_to_host (sig);
3919 else
3920 signal = 0;
3921 myresume (own_buf, 0, signal);
3922 break;
3923 case 'S':
3924 require_running (own_buf);
3925 hex2bin (own_buf + 1, &sig, 1);
3926 if (gdb_signal_to_host_p (sig))
3927 signal = gdb_signal_to_host (sig);
3928 else
3929 signal = 0;
3930 myresume (own_buf, 1, signal);
3931 break;
3932 case 'c':
3933 require_running (own_buf);
3934 signal = 0;
3935 myresume (own_buf, 0, signal);
3936 break;
3937 case 's':
3938 require_running (own_buf);
3939 signal = 0;
3940 myresume (own_buf, 1, signal);
3941 break;
3942 case 'Z': /* insert_ ... */
3943 /* Fallthrough. */
3944 case 'z': /* remove_ ... */
3945 {
3946 char *dataptr;
3947 ULONGEST addr;
3948 int len;
3949 char type = own_buf[1];
3950 int res;
3951 const int insert = ch == 'Z';
3952 char *p = &own_buf[3];
3953
3954 p = unpack_varlen_hex (p, &addr);
3955 len = strtol (p + 1, &dataptr, 16);
3956
3957 if (insert)
3958 {
3959 struct breakpoint *bp;
3960
3961 bp = set_gdb_breakpoint (type, addr, len, &res);
3962 if (bp != NULL)
3963 {
3964 res = 0;
3965
3966 /* GDB may have sent us a list of *point parameters to
3967 be evaluated on the target's side. Read such list
3968 here. If we already have a list of parameters, GDB
3969 is telling us to drop that list and use this one
3970 instead. */
3971 clear_breakpoint_conditions_and_commands (bp);
3972 process_point_options (bp, &dataptr);
3973 }
3974 }
3975 else
3976 res = delete_gdb_breakpoint (type, addr, len);
3977
3978 if (res == 0)
3979 write_ok (own_buf);
3980 else if (res == 1)
3981 /* Unsupported. */
3982 own_buf[0] = '\0';
3983 else
3984 write_enn (own_buf);
3985 break;
3986 }
3987 case 'k':
3988 response_needed = 0;
3989 if (!target_running ())
3990 /* The packet we received doesn't make sense - but we can't
3991 reply to it, either. */
3992 return 0;
3993
3994 fprintf (stderr, "Killing all inferiors\n");
3995 for_each_inferior (&all_processes, kill_inferior_callback);
3996
3997 /* When using the extended protocol, we wait with no program
3998 running. The traditional protocol will exit instead. */
3999 if (extended_protocol)
4000 {
4001 last_status.kind = TARGET_WAITKIND_EXITED;
4002 last_status.value.sig = GDB_SIGNAL_KILL;
4003 return 0;
4004 }
4005 else
4006 exit (0);
4007
4008 case 'T':
4009 {
4010 ptid_t gdb_id, thread_id;
4011
4012 require_running (own_buf);
4013
4014 gdb_id = read_ptid (&own_buf[1], NULL);
4015 thread_id = gdb_id_to_thread_id (gdb_id);
4016 if (ptid_equal (thread_id, null_ptid))
4017 {
4018 write_enn (own_buf);
4019 break;
4020 }
4021
4022 if (mythread_alive (thread_id))
4023 write_ok (own_buf);
4024 else
4025 write_enn (own_buf);
4026 }
4027 break;
4028 case 'R':
4029 response_needed = 0;
4030
4031 /* Restarting the inferior is only supported in the extended
4032 protocol. */
4033 if (extended_protocol)
4034 {
4035 if (target_running ())
4036 for_each_inferior (&all_processes,
4037 kill_inferior_callback);
4038 fprintf (stderr, "GDBserver restarting\n");
4039
4040 /* Wait till we are at 1st instruction in prog. */
4041 if (program_argv != NULL)
4042 start_inferior (program_argv);
4043 else
4044 {
4045 last_status.kind = TARGET_WAITKIND_EXITED;
4046 last_status.value.sig = GDB_SIGNAL_KILL;
4047 }
4048 return 0;
4049 }
4050 else
4051 {
4052 /* It is a request we don't understand. Respond with an
4053 empty packet so that gdb knows that we don't support this
4054 request. */
4055 own_buf[0] = '\0';
4056 break;
4057 }
4058 case 'v':
4059 /* Extended (long) request. */
4060 handle_v_requests (own_buf, packet_len, &new_packet_len);
4061 break;
4062
4063 default:
4064 /* It is a request we don't understand. Respond with an empty
4065 packet so that gdb knows that we don't support this
4066 request. */
4067 own_buf[0] = '\0';
4068 break;
4069 }
4070
4071 if (new_packet_len != -1)
4072 putpkt_binary (own_buf, new_packet_len);
4073 else
4074 putpkt (own_buf);
4075
4076 response_needed = 0;
4077
4078 if (!extended_protocol && have_ran && !target_running ())
4079 {
4080 /* In non-stop, defer exiting until GDB had a chance to query
4081 the whole vStopped list (until it gets an OK). */
4082 if (QUEUE_is_empty (notif_event_p, notif_stop.queue))
4083 {
4084 /* Be transparent when GDB is connected through stdio -- no
4085 need to spam GDB's console. */
4086 if (!remote_connection_is_stdio ())
4087 fprintf (stderr, "GDBserver exiting\n");
4088 remote_close ();
4089 exit (0);
4090 }
4091 }
4092
4093 if (exit_requested)
4094 return -1;
4095
4096 return 0;
4097 }
4098
4099 /* Event-loop callback for serial events. */
4100
4101 int
4102 handle_serial_event (int err, gdb_client_data client_data)
4103 {
4104 if (debug_threads)
4105 debug_printf ("handling possible serial event\n");
4106
4107 /* Really handle it. */
4108 if (process_serial_event () < 0)
4109 return -1;
4110
4111 /* Be sure to not change the selected thread behind GDB's back.
4112 Important in the non-stop mode asynchronous protocol. */
4113 set_desired_thread (1);
4114
4115 return 0;
4116 }
4117
4118 /* Event-loop callback for target events. */
4119
4120 int
4121 handle_target_event (int err, gdb_client_data client_data)
4122 {
4123 if (debug_threads)
4124 debug_printf ("handling possible target event\n");
4125
4126 last_ptid = mywait (minus_one_ptid, &last_status,
4127 TARGET_WNOHANG, 1);
4128
4129 if (last_status.kind == TARGET_WAITKIND_NO_RESUMED)
4130 {
4131 /* No RSP support for this yet. */
4132 }
4133 else if (last_status.kind != TARGET_WAITKIND_IGNORE)
4134 {
4135 int pid = ptid_get_pid (last_ptid);
4136 struct process_info *process = find_process_pid (pid);
4137 int forward_event = !gdb_connected () || process->gdb_detached;
4138
4139 if (last_status.kind == TARGET_WAITKIND_EXITED
4140 || last_status.kind == TARGET_WAITKIND_SIGNALLED)
4141 {
4142 mark_breakpoints_out (process);
4143 mourn_inferior (process);
4144 }
4145 else
4146 {
4147 /* We're reporting this thread as stopped. Update its
4148 "want-stopped" state to what the client wants, until it
4149 gets a new resume action. */
4150 current_thread->last_resume_kind = resume_stop;
4151 current_thread->last_status = last_status;
4152 }
4153
4154 if (forward_event)
4155 {
4156 if (!target_running ())
4157 {
4158 /* The last process exited. We're done. */
4159 exit (0);
4160 }
4161
4162 if (last_status.kind == TARGET_WAITKIND_STOPPED)
4163 {
4164 /* A thread stopped with a signal, but gdb isn't
4165 connected to handle it. Pass it down to the
4166 inferior, as if it wasn't being traced. */
4167 struct thread_resume resume_info;
4168
4169 if (debug_threads)
4170 debug_printf ("GDB not connected; forwarding event %d for"
4171 " [%s]\n",
4172 (int) last_status.kind,
4173 target_pid_to_str (last_ptid));
4174
4175 resume_info.thread = last_ptid;
4176 resume_info.kind = resume_continue;
4177 resume_info.sig = gdb_signal_to_host (last_status.value.sig);
4178 (*the_target->resume) (&resume_info, 1);
4179 }
4180 else if (debug_threads)
4181 debug_printf ("GDB not connected; ignoring event %d for [%s]\n",
4182 (int) last_status.kind,
4183 target_pid_to_str (last_ptid));
4184 }
4185 else
4186 {
4187 struct vstop_notif *vstop_notif
4188 = xmalloc (sizeof (struct vstop_notif));
4189
4190 vstop_notif->status = last_status;
4191 vstop_notif->ptid = last_ptid;
4192 /* Push Stop notification. */
4193 notif_push (&notif_stop,
4194 (struct notif_event *) vstop_notif);
4195 }
4196 }
4197
4198 /* Be sure to not change the selected thread behind GDB's back.
4199 Important in the non-stop mode asynchronous protocol. */
4200 set_desired_thread (1);
4201
4202 return 0;
4203 }
This page took 0.154085 seconds and 5 git commands to generate.