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