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