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