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