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