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