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