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