1 /* Main code for remote server for GDB.
2 Copyright (C) 1989-2014 Free Software Foundation, Inc.
4 This file is part of GDB.
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.
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.
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/>. */
20 #include "gdbthread.h"
30 #include "btrace-common.h"
31 #include "filestuff.h"
32 #include "tracepoint.h"
36 /* The thread set with an `Hc' packet. `Hc' is deprecated in favor of
37 `vCont'. Note the multi-process extensions made `vCont' a
38 requirement, so `Hc pPID.TID' is pretty much undefined. So
39 CONT_THREAD can be null_ptid for no `Hc' thread, minus_one_ptid for
40 resuming all threads of the process (again, `Hc' isn't used for
41 multi-process), or a specific thread ptid_t.
43 We also set this when handling a single-thread `vCont' resume, as
44 some places in the backends check it to know when (and for which
45 thread) single-thread scheduler-locking is in effect. */
48 /* The thread set with an `Hg' packet. */
49 ptid_t general_thread;
53 static int extended_protocol;
54 static int response_needed;
55 static int exit_requested;
57 /* --once: Exit after the first connection has closed. */
63 /* Whether we should attempt to disable the operating system's address
64 space randomization feature before starting an inferior. */
65 int disable_randomization = 1;
67 static char **program_argv, **wrapper_argv;
69 /* Enable miscellaneous debugging output. The name is historical - it
70 was originally used to debug LinuxThreads support. */
73 /* Enable debugging of h/w breakpoint/watchpoint support. */
76 int pass_signals[GDB_SIGNAL_LAST];
77 int program_signals[GDB_SIGNAL_LAST];
78 int program_signals_p;
82 /* The PID of the originally created or attached inferior. Used to
83 send signals to the process when GDB sends us an asynchronous interrupt
84 (user hitting Control-C in the client), and to wait for the child to exit
85 when no longer debugging it. */
87 unsigned long signal_pid;
90 /* A file descriptor for the controlling terminal. */
93 /* TERMINAL_FD's original foreground group. */
94 pid_t old_foreground_pgrp;
96 /* Hand back terminal ownership to the original foreground group. */
99 restore_old_foreground_pgrp (void)
101 tcsetpgrp (terminal_fd, old_foreground_pgrp);
105 /* Set if you want to disable optional thread related packets support
106 in gdbserver, for the sake of testing GDB against stubs that don't
108 int disable_packet_vCont;
109 int disable_packet_Tthread;
110 int disable_packet_qC;
111 int disable_packet_qfThreadInfo;
113 /* Last status reported to GDB. */
114 static struct target_waitstatus last_status;
115 static ptid_t last_ptid;
117 static char *own_buf;
118 static unsigned char *mem_buf;
120 /* A sub-class of 'struct notif_event' for stop, holding information
121 relative to a single stop reply. We keep a queue of these to
122 push to GDB in non-stop mode. */
126 struct notif_event base;
128 /* Thread or process that got the event. */
132 struct target_waitstatus status;
135 DEFINE_QUEUE_P (notif_event_p);
137 /* Put a stop reply to the stop reply queue. */
140 queue_stop_reply (ptid_t ptid, struct target_waitstatus *status)
142 struct vstop_notif *new_notif = xmalloc (sizeof (*new_notif));
144 new_notif->ptid = ptid;
145 new_notif->status = *status;
147 notif_event_enque (¬if_stop, (struct notif_event *) new_notif);
151 remove_all_on_match_pid (QUEUE (notif_event_p) *q,
152 QUEUE_ITER (notif_event_p) *iter,
153 struct notif_event *event,
159 || ptid_get_pid (((struct vstop_notif *) event)->ptid) == *pid)
161 if (q->free_func != NULL)
162 q->free_func (event);
164 QUEUE_remove_elem (notif_event_p, q, iter);
170 /* Get rid of the currently pending stop replies for PID. If PID is
171 -1, then apply to all processes. */
174 discard_queued_stop_replies (int pid)
176 QUEUE_iterate (notif_event_p, notif_stop.queue,
177 remove_all_on_match_pid, &pid);
181 vstop_notif_reply (struct notif_event *event, char *own_buf)
183 struct vstop_notif *vstop = (struct vstop_notif *) event;
185 prepare_resume_reply (own_buf, vstop->ptid, &vstop->status);
188 struct notif_server notif_stop =
190 "vStopped", "Stop", NULL, vstop_notif_reply,
194 target_running (void)
196 return all_threads.head != NULL;
200 start_inferior (char **argv)
202 char **new_argv = argv;
204 if (wrapper_argv != NULL)
208 for (i = 0; wrapper_argv[i] != NULL; i++)
210 for (i = 0; argv[i] != NULL; i++)
212 new_argv = alloca (sizeof (char *) * count);
214 for (i = 0; wrapper_argv[i] != NULL; i++)
215 new_argv[count++] = wrapper_argv[i];
216 for (i = 0; argv[i] != NULL; i++)
217 new_argv[count++] = argv[i];
218 new_argv[count] = NULL;
224 for (i = 0; new_argv[i]; ++i)
225 fprintf (stderr, "new_argv[%d] = \"%s\"\n", i, new_argv[i]);
230 signal (SIGTTOU, SIG_DFL);
231 signal (SIGTTIN, SIG_DFL);
234 /* Clear this so the backend doesn't get confused, thinking
235 CONT_THREAD died, and it needs to resume all threads. */
236 cont_thread = null_ptid;
238 signal_pid = create_inferior (new_argv[0], new_argv);
240 /* FIXME: we don't actually know at this point that the create
241 actually succeeded. We won't know that until we wait. */
242 fprintf (stderr, "Process %s created; pid = %ld\n", argv[0],
247 signal (SIGTTOU, SIG_IGN);
248 signal (SIGTTIN, SIG_IGN);
249 terminal_fd = fileno (stderr);
250 old_foreground_pgrp = tcgetpgrp (terminal_fd);
251 tcsetpgrp (terminal_fd, signal_pid);
252 atexit (restore_old_foreground_pgrp);
255 if (wrapper_argv != NULL)
257 struct thread_resume resume_info;
259 memset (&resume_info, 0, sizeof (resume_info));
260 resume_info.thread = pid_to_ptid (signal_pid);
261 resume_info.kind = resume_continue;
264 last_ptid = mywait (pid_to_ptid (signal_pid), &last_status, 0, 0);
266 if (last_status.kind != TARGET_WAITKIND_STOPPED)
271 (*the_target->resume) (&resume_info, 1);
273 last_ptid = mywait (pid_to_ptid (signal_pid), &last_status, 0, 0);
274 if (last_status.kind != TARGET_WAITKIND_STOPPED)
277 current_inferior->last_resume_kind = resume_stop;
278 current_inferior->last_status = last_status;
280 while (last_status.value.sig != GDB_SIGNAL_TRAP);
285 /* Wait till we are at 1st instruction in program, return new pid
286 (assuming success). */
287 last_ptid = mywait (pid_to_ptid (signal_pid), &last_status, 0, 0);
289 if (last_status.kind != TARGET_WAITKIND_EXITED
290 && last_status.kind != TARGET_WAITKIND_SIGNALLED)
292 current_inferior->last_resume_kind = resume_stop;
293 current_inferior->last_status = last_status;
300 attach_inferior (int pid)
302 /* myattach should return -1 if attaching is unsupported,
303 0 if it succeeded, and call error() otherwise. */
305 if (myattach (pid) != 0)
308 fprintf (stderr, "Attached; pid = %d\n", pid);
311 /* FIXME - It may be that we should get the SIGNAL_PID from the
312 attach function, so that it can be the main thread instead of
313 whichever we were told to attach to. */
316 /* Clear this so the backend doesn't get confused, thinking
317 CONT_THREAD died, and it needs to resume all threads. */
318 cont_thread = null_ptid;
322 last_ptid = mywait (pid_to_ptid (pid), &last_status, 0, 0);
324 /* GDB knows to ignore the first SIGSTOP after attaching to a running
325 process using the "attach" command, but this is different; it's
326 just using "target remote". Pretend it's just starting up. */
327 if (last_status.kind == TARGET_WAITKIND_STOPPED
328 && last_status.value.sig == GDB_SIGNAL_STOP)
329 last_status.value.sig = GDB_SIGNAL_TRAP;
331 current_inferior->last_resume_kind = resume_stop;
332 current_inferior->last_status = last_status;
338 extern int remote_debug;
340 /* Decode a qXfer read request. Return 0 if everything looks OK,
344 decode_xfer_read (char *buf, CORE_ADDR *ofs, unsigned int *len)
346 /* After the read marker and annex, qXfer looks like a
347 traditional 'm' packet. */
348 decode_m_packet (buf, ofs, len);
354 decode_xfer (char *buf, char **object, char **rw, char **annex, char **offset)
356 /* Extract and NUL-terminate the object. */
358 while (*buf && *buf != ':')
364 /* Extract and NUL-terminate the read/write action. */
366 while (*buf && *buf != ':')
372 /* Extract and NUL-terminate the annex. */
374 while (*buf && *buf != ':')
384 /* Write the response to a successful qXfer read. Returns the
385 length of the (binary) data stored in BUF, corresponding
386 to as much of DATA/LEN as we could fit. IS_MORE controls
387 the first character of the response. */
389 write_qxfer_response (char *buf, const void *data, int len, int is_more)
398 return remote_escape_output (data, len, (unsigned char *) buf + 1, &out_len,
402 /* Handle btrace enabling. */
405 handle_btrace_enable (struct thread_info *thread)
407 if (thread->btrace != NULL)
408 return "E.Btrace already enabled.";
410 thread->btrace = target_enable_btrace (thread->entry.id);
411 if (thread->btrace == NULL)
412 return "E.Could not enable btrace.";
417 /* Handle btrace disabling. */
420 handle_btrace_disable (struct thread_info *thread)
423 if (thread->btrace == NULL)
424 return "E.Branch tracing not enabled.";
426 if (target_disable_btrace (thread->btrace) != 0)
427 return "E.Could not disable branch tracing.";
429 thread->btrace = NULL;
433 /* Handle the "Qbtrace" packet. */
436 handle_btrace_general_set (char *own_buf)
438 struct thread_info *thread;
442 if (strncmp ("Qbtrace:", own_buf, strlen ("Qbtrace:")) != 0)
445 op = own_buf + strlen ("Qbtrace:");
447 if (!target_supports_btrace ())
449 strcpy (own_buf, "E.Target does not support branch tracing.");
453 if (ptid_equal (general_thread, null_ptid)
454 || ptid_equal (general_thread, minus_one_ptid))
456 strcpy (own_buf, "E.Must select a single thread.");
460 thread = find_thread_ptid (general_thread);
463 strcpy (own_buf, "E.No such thread.");
469 if (strcmp (op, "bts") == 0)
470 err = handle_btrace_enable (thread);
471 else if (strcmp (op, "off") == 0)
472 err = handle_btrace_disable (thread);
474 err = "E.Bad Qbtrace operation. Use bts or off.";
477 strcpy (own_buf, err);
484 /* Handle all of the extended 'Q' packets. */
487 handle_general_set (char *own_buf)
489 if (strncmp ("QPassSignals:", own_buf, strlen ("QPassSignals:")) == 0)
491 int numsigs = (int) GDB_SIGNAL_LAST, i;
492 const char *p = own_buf + strlen ("QPassSignals:");
495 p = decode_address_to_semicolon (&cursig, p);
496 for (i = 0; i < numsigs; i++)
502 /* Keep looping, to clear the remaining signals. */
505 p = decode_address_to_semicolon (&cursig, p);
510 strcpy (own_buf, "OK");
514 if (strncmp ("QProgramSignals:", own_buf, strlen ("QProgramSignals:")) == 0)
516 int numsigs = (int) GDB_SIGNAL_LAST, i;
517 const char *p = own_buf + strlen ("QProgramSignals:");
520 program_signals_p = 1;
522 p = decode_address_to_semicolon (&cursig, p);
523 for (i = 0; i < numsigs; i++)
527 program_signals[i] = 1;
529 /* Keep looping, to clear the remaining signals. */
532 p = decode_address_to_semicolon (&cursig, p);
535 program_signals[i] = 0;
537 strcpy (own_buf, "OK");
541 if (strcmp (own_buf, "QStartNoAckMode") == 0)
545 fprintf (stderr, "[noack mode enabled]\n");
554 if (strncmp (own_buf, "QNonStop:", 9) == 0)
556 char *mode = own_buf + 9;
560 if (strcmp (mode, "0") == 0)
562 else if (strcmp (mode, "1") == 0)
566 /* We don't know what this mode is, so complain to
568 fprintf (stderr, "Unknown non-stop mode requested: %s\n",
574 req_str = req ? "non-stop" : "all-stop";
575 if (start_non_stop (req) != 0)
577 fprintf (stderr, "Setting %s mode failed\n", req_str);
585 fprintf (stderr, "[%s mode enabled]\n", req_str);
591 if (strncmp ("QDisableRandomization:", own_buf,
592 strlen ("QDisableRandomization:")) == 0)
594 char *packet = own_buf + strlen ("QDisableRandomization:");
597 unpack_varlen_hex (packet, &setting);
598 disable_randomization = setting;
602 if (disable_randomization)
603 fprintf (stderr, "[address space randomization disabled]\n");
605 fprintf (stderr, "[address space randomization enabled]\n");
612 if (target_supports_tracepoints ()
613 && handle_tracepoint_general_set (own_buf))
616 if (strncmp ("QAgent:", own_buf, strlen ("QAgent:")) == 0)
618 char *mode = own_buf + strlen ("QAgent:");
621 if (strcmp (mode, "0") == 0)
623 else if (strcmp (mode, "1") == 0)
627 /* We don't know what this value is, so complain to GDB. */
628 sprintf (own_buf, "E.Unknown QAgent value");
632 /* Update the flag. */
635 fprintf (stderr, "[%s agent]\n", req ? "Enable" : "Disable");
640 if (handle_btrace_general_set (own_buf))
643 /* Otherwise we didn't know what packet it was. Say we didn't
649 get_features_xml (const char *annex)
651 const struct target_desc *desc = current_target_desc ();
653 /* `desc->xmltarget' defines what to return when looking for the
654 "target.xml" file. Its contents can either be verbatim XML code
655 (prefixed with a '@') or else the name of the actual XML file to
656 be used in place of "target.xml".
658 This variable is set up from the auto-generated
659 init_registers_... routine for the current target. */
661 if (desc->xmltarget != NULL && strcmp (annex, "target.xml") == 0)
663 if (*desc->xmltarget == '@')
664 return desc->xmltarget + 1;
666 annex = desc->xmltarget;
671 extern const char *const xml_builtin[][2];
674 /* Look for the annex. */
675 for (i = 0; xml_builtin[i][0] != NULL; i++)
676 if (strcmp (annex, xml_builtin[i][0]) == 0)
679 if (xml_builtin[i][0] != NULL)
680 return xml_builtin[i][1];
688 monitor_show_help (void)
690 monitor_output ("The following monitor commands are supported:\n");
691 monitor_output (" set debug <0|1>\n");
692 monitor_output (" Enable general debugging messages\n");
693 monitor_output (" set debug-hw-points <0|1>\n");
694 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
695 monitor_output (" set remote-debug <0|1>\n");
696 monitor_output (" Enable remote protocol debugging messages\n");
697 monitor_output (" exit\n");
698 monitor_output (" Quit GDBserver\n");
701 /* Read trace frame or inferior memory. Returns the number of bytes
702 actually read, zero when no further transfer is possible, and -1 on
703 error. Return of a positive value smaller than LEN does not
704 indicate there's no more to be read, only the end of the transfer.
705 E.g., when GDB reads memory from a traceframe, a first request may
706 be served from a memory block that does not cover the whole request
707 length. A following request gets the rest served from either
708 another block (of the same traceframe) or from the read-only
712 gdb_read_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
716 if (current_traceframe >= 0)
719 ULONGEST length = len;
721 if (traceframe_read_mem (current_traceframe,
722 memaddr, myaddr, len, &nbytes))
724 /* Data read from trace buffer, we're done. */
727 if (!in_readonly_region (memaddr, length))
729 /* Otherwise we have a valid readonly case, fall through. */
730 /* (assume no half-trace half-real blocks for now) */
733 res = prepare_to_access_memory ();
736 res = read_inferior_memory (memaddr, myaddr, len);
737 done_accessing_memory ();
739 return res == 0 ? len : -1;
745 /* Write trace frame or inferior memory. Actually, writing to trace
746 frames is forbidden. */
749 gdb_write_memory (CORE_ADDR memaddr, const unsigned char *myaddr, int len)
751 if (current_traceframe >= 0)
757 ret = prepare_to_access_memory ();
760 ret = write_inferior_memory (memaddr, myaddr, len);
761 done_accessing_memory ();
767 /* Subroutine of handle_search_memory to simplify it. */
770 handle_search_memory_1 (CORE_ADDR start_addr, CORE_ADDR search_space_len,
771 gdb_byte *pattern, unsigned pattern_len,
772 gdb_byte *search_buf,
773 unsigned chunk_size, unsigned search_buf_size,
774 CORE_ADDR *found_addrp)
776 /* Prime the search buffer. */
778 if (gdb_read_memory (start_addr, search_buf, search_buf_size)
781 warning ("Unable to access %ld bytes of target "
782 "memory at 0x%lx, halting search.",
783 (long) search_buf_size, (long) start_addr);
787 /* Perform the search.
789 The loop is kept simple by allocating [N + pattern-length - 1] bytes.
790 When we've scanned N bytes we copy the trailing bytes to the start and
791 read in another N bytes. */
793 while (search_space_len >= pattern_len)
796 unsigned nr_search_bytes = (search_space_len < search_buf_size
800 found_ptr = memmem (search_buf, nr_search_bytes, pattern, pattern_len);
802 if (found_ptr != NULL)
804 CORE_ADDR found_addr = start_addr + (found_ptr - search_buf);
805 *found_addrp = found_addr;
809 /* Not found in this chunk, skip to next chunk. */
811 /* Don't let search_space_len wrap here, it's unsigned. */
812 if (search_space_len >= chunk_size)
813 search_space_len -= chunk_size;
815 search_space_len = 0;
817 if (search_space_len >= pattern_len)
819 unsigned keep_len = search_buf_size - chunk_size;
820 CORE_ADDR read_addr = start_addr + chunk_size + keep_len;
823 /* Copy the trailing part of the previous iteration to the front
824 of the buffer for the next iteration. */
825 memcpy (search_buf, search_buf + chunk_size, keep_len);
827 nr_to_read = (search_space_len - keep_len < chunk_size
828 ? search_space_len - keep_len
831 if (gdb_read_memory (read_addr, search_buf + keep_len,
832 nr_to_read) != search_buf_size)
834 warning ("Unable to access %ld bytes of target memory "
835 "at 0x%lx, halting search.",
836 (long) nr_to_read, (long) read_addr);
840 start_addr += chunk_size;
849 /* Handle qSearch:memory packets. */
852 handle_search_memory (char *own_buf, int packet_len)
854 CORE_ADDR start_addr;
855 CORE_ADDR search_space_len;
857 unsigned int pattern_len;
858 /* NOTE: also defined in find.c testcase. */
859 #define SEARCH_CHUNK_SIZE 16000
860 const unsigned chunk_size = SEARCH_CHUNK_SIZE;
861 /* Buffer to hold memory contents for searching. */
862 gdb_byte *search_buf;
863 unsigned search_buf_size;
865 CORE_ADDR found_addr;
866 int cmd_name_len = sizeof ("qSearch:memory:") - 1;
868 pattern = malloc (packet_len);
871 error ("Unable to allocate memory to perform the search");
872 strcpy (own_buf, "E00");
875 if (decode_search_memory_packet (own_buf + cmd_name_len,
876 packet_len - cmd_name_len,
877 &start_addr, &search_space_len,
878 pattern, &pattern_len) < 0)
881 error ("Error in parsing qSearch:memory packet");
882 strcpy (own_buf, "E00");
886 search_buf_size = chunk_size + pattern_len - 1;
888 /* No point in trying to allocate a buffer larger than the search space. */
889 if (search_space_len < search_buf_size)
890 search_buf_size = search_space_len;
892 search_buf = malloc (search_buf_size);
893 if (search_buf == NULL)
896 error ("Unable to allocate memory to perform the search");
897 strcpy (own_buf, "E00");
901 found = handle_search_memory_1 (start_addr, search_space_len,
902 pattern, pattern_len,
903 search_buf, chunk_size, search_buf_size,
907 sprintf (own_buf, "1,%lx", (long) found_addr);
909 strcpy (own_buf, "0");
911 strcpy (own_buf, "E00");
917 #define require_running(BUF) \
918 if (!target_running ()) \
924 /* Handle monitor commands not handled by target-specific handlers. */
927 handle_monitor_command (char *mon, char *own_buf)
929 if (strcmp (mon, "set debug 1") == 0)
932 monitor_output ("Debug output enabled.\n");
934 else if (strcmp (mon, "set debug 0") == 0)
937 monitor_output ("Debug output disabled.\n");
939 else if (strcmp (mon, "set debug-hw-points 1") == 0)
942 monitor_output ("H/W point debugging output enabled.\n");
944 else if (strcmp (mon, "set debug-hw-points 0") == 0)
947 monitor_output ("H/W point debugging output disabled.\n");
949 else if (strcmp (mon, "set remote-debug 1") == 0)
952 monitor_output ("Protocol debug output enabled.\n");
954 else if (strcmp (mon, "set remote-debug 0") == 0)
957 monitor_output ("Protocol debug output disabled.\n");
959 else if (strcmp (mon, "help") == 0)
960 monitor_show_help ();
961 else if (strcmp (mon, "exit") == 0)
965 monitor_output ("Unknown monitor command.\n\n");
966 monitor_show_help ();
971 /* Associates a callback with each supported qXfer'able object. */
975 /* The object this handler handles. */
978 /* Request that the target transfer up to LEN 8-bit bytes of the
979 target's OBJECT. The OFFSET, for a seekable object, specifies
980 the starting point. The ANNEX can be used to provide additional
981 data-specific information to the target.
983 Return the number of bytes actually transfered, zero when no
984 further transfer is possible, -1 on error, -2 when the transfer
985 is not supported, and -3 on a verbose error message that should
986 be preserved. Return of a positive value smaller than LEN does
987 not indicate the end of the object, only the end of the transfer.
989 One, and only one, of readbuf or writebuf must be non-NULL. */
990 int (*xfer) (const char *annex,
991 gdb_byte *readbuf, const gdb_byte *writebuf,
992 ULONGEST offset, LONGEST len);
995 /* Handle qXfer:auxv:read. */
998 handle_qxfer_auxv (const char *annex,
999 gdb_byte *readbuf, const gdb_byte *writebuf,
1000 ULONGEST offset, LONGEST len)
1002 if (the_target->read_auxv == NULL || writebuf != NULL)
1005 if (annex[0] != '\0' || !target_running ())
1008 return (*the_target->read_auxv) (offset, readbuf, len);
1011 /* Handle qXfer:features:read. */
1014 handle_qxfer_features (const char *annex,
1015 gdb_byte *readbuf, const gdb_byte *writebuf,
1016 ULONGEST offset, LONGEST len)
1018 const char *document;
1021 if (writebuf != NULL)
1024 if (!target_running ())
1027 /* Grab the correct annex. */
1028 document = get_features_xml (annex);
1029 if (document == NULL)
1032 total_len = strlen (document);
1034 if (offset > total_len)
1037 if (offset + len > total_len)
1038 len = total_len - offset;
1040 memcpy (readbuf, document + offset, len);
1044 /* Handle qXfer:libraries:read. */
1047 handle_qxfer_libraries (const char *annex,
1048 gdb_byte *readbuf, const gdb_byte *writebuf,
1049 ULONGEST offset, LONGEST len)
1051 unsigned int total_len;
1053 struct inferior_list_entry *dll_ptr;
1055 if (writebuf != NULL)
1058 if (annex[0] != '\0' || !target_running ())
1061 /* Over-estimate the necessary memory. Assume that every character
1062 in the library name must be escaped. */
1064 for (dll_ptr = all_dlls.head; dll_ptr != NULL; dll_ptr = dll_ptr->next)
1065 total_len += 128 + 6 * strlen (((struct dll_info *) dll_ptr)->name);
1067 document = malloc (total_len);
1068 if (document == NULL)
1071 strcpy (document, "<library-list>\n");
1072 p = document + strlen (document);
1074 for (dll_ptr = all_dlls.head; dll_ptr != NULL; dll_ptr = dll_ptr->next)
1076 struct dll_info *dll = (struct dll_info *) dll_ptr;
1079 strcpy (p, " <library name=\"");
1081 name = xml_escape_text (dll->name);
1085 strcpy (p, "\"><segment address=\"");
1087 sprintf (p, "0x%lx", (long) dll->base_addr);
1089 strcpy (p, "\"/></library>\n");
1093 strcpy (p, "</library-list>\n");
1095 total_len = strlen (document);
1097 if (offset > total_len)
1103 if (offset + len > total_len)
1104 len = total_len - offset;
1106 memcpy (readbuf, document + offset, len);
1111 /* Handle qXfer:libraries-svr4:read. */
1114 handle_qxfer_libraries_svr4 (const char *annex,
1115 gdb_byte *readbuf, const gdb_byte *writebuf,
1116 ULONGEST offset, LONGEST len)
1118 if (writebuf != NULL)
1121 if (!target_running () || the_target->qxfer_libraries_svr4 == NULL)
1124 return the_target->qxfer_libraries_svr4 (annex, readbuf, writebuf, offset, len);
1127 /* Handle qXfer:osadata:read. */
1130 handle_qxfer_osdata (const char *annex,
1131 gdb_byte *readbuf, const gdb_byte *writebuf,
1132 ULONGEST offset, LONGEST len)
1134 if (the_target->qxfer_osdata == NULL || writebuf != NULL)
1137 return (*the_target->qxfer_osdata) (annex, readbuf, NULL, offset, len);
1140 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1143 handle_qxfer_siginfo (const char *annex,
1144 gdb_byte *readbuf, const gdb_byte *writebuf,
1145 ULONGEST offset, LONGEST len)
1147 if (the_target->qxfer_siginfo == NULL)
1150 if (annex[0] != '\0' || !target_running ())
1153 return (*the_target->qxfer_siginfo) (annex, readbuf, writebuf, offset, len);
1156 /* Handle qXfer:spu:read and qXfer:spu:write. */
1159 handle_qxfer_spu (const char *annex,
1160 gdb_byte *readbuf, const gdb_byte *writebuf,
1161 ULONGEST offset, LONGEST len)
1163 if (the_target->qxfer_spu == NULL)
1166 if (!target_running ())
1169 return (*the_target->qxfer_spu) (annex, readbuf, writebuf, offset, len);
1172 /* Handle qXfer:statictrace:read. */
1175 handle_qxfer_statictrace (const char *annex,
1176 gdb_byte *readbuf, const gdb_byte *writebuf,
1177 ULONGEST offset, LONGEST len)
1181 if (writebuf != NULL)
1184 if (annex[0] != '\0' || !target_running () || current_traceframe == -1)
1187 if (traceframe_read_sdata (current_traceframe, offset,
1188 readbuf, len, &nbytes))
1193 /* Helper for handle_qxfer_threads. */
1196 handle_qxfer_threads_proper (struct buffer *buffer)
1198 struct inferior_list_entry *thread;
1200 buffer_grow_str (buffer, "<threads>\n");
1202 for (thread = all_threads.head; thread; thread = thread->next)
1204 ptid_t ptid = thread_to_gdb_id ((struct thread_info *)thread);
1206 int core = target_core_of_thread (ptid);
1209 write_ptid (ptid_s, ptid);
1213 sprintf (core_s, "%d", core);
1214 buffer_xml_printf (buffer, "<thread id=\"%s\" core=\"%s\"/>\n",
1219 buffer_xml_printf (buffer, "<thread id=\"%s\"/>\n",
1224 buffer_grow_str0 (buffer, "</threads>\n");
1227 /* Handle qXfer:threads:read. */
1230 handle_qxfer_threads (const char *annex,
1231 gdb_byte *readbuf, const gdb_byte *writebuf,
1232 ULONGEST offset, LONGEST len)
1234 static char *result = 0;
1235 static unsigned int result_length = 0;
1237 if (writebuf != NULL)
1240 if (!target_running () || annex[0] != '\0')
1245 struct buffer buffer;
1246 /* When asked for data at offset 0, generate everything and store into
1247 'result'. Successive reads will be served off 'result'. */
1251 buffer_init (&buffer);
1253 handle_qxfer_threads_proper (&buffer);
1255 result = buffer_finish (&buffer);
1256 result_length = strlen (result);
1257 buffer_free (&buffer);
1260 if (offset >= result_length)
1262 /* We're out of data. */
1269 if (len > result_length - offset)
1270 len = result_length - offset;
1272 memcpy (readbuf, result + offset, len);
1277 /* Handle qXfer:traceframe-info:read. */
1280 handle_qxfer_traceframe_info (const char *annex,
1281 gdb_byte *readbuf, const gdb_byte *writebuf,
1282 ULONGEST offset, LONGEST len)
1284 static char *result = 0;
1285 static unsigned int result_length = 0;
1287 if (writebuf != NULL)
1290 if (!target_running () || annex[0] != '\0' || current_traceframe == -1)
1295 struct buffer buffer;
1297 /* When asked for data at offset 0, generate everything and
1298 store into 'result'. Successive reads will be served off
1302 buffer_init (&buffer);
1304 traceframe_read_info (current_traceframe, &buffer);
1306 result = buffer_finish (&buffer);
1307 result_length = strlen (result);
1308 buffer_free (&buffer);
1311 if (offset >= result_length)
1313 /* We're out of data. */
1320 if (len > result_length - offset)
1321 len = result_length - offset;
1323 memcpy (readbuf, result + offset, len);
1327 /* Handle qXfer:fdpic:read. */
1330 handle_qxfer_fdpic (const char *annex, gdb_byte *readbuf,
1331 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
1333 if (the_target->read_loadmap == NULL)
1336 if (!target_running ())
1339 return (*the_target->read_loadmap) (annex, offset, readbuf, len);
1342 /* Handle qXfer:btrace:read. */
1345 handle_qxfer_btrace (const char *annex,
1346 gdb_byte *readbuf, const gdb_byte *writebuf,
1347 ULONGEST offset, LONGEST len)
1349 static struct buffer cache;
1350 struct thread_info *thread;
1353 if (the_target->read_btrace == NULL || writebuf != NULL)
1356 if (!target_running ())
1359 if (ptid_equal (general_thread, null_ptid)
1360 || ptid_equal (general_thread, minus_one_ptid))
1362 strcpy (own_buf, "E.Must select a single thread.");
1366 thread = find_thread_ptid (general_thread);
1369 strcpy (own_buf, "E.No such thread.");
1373 if (thread->btrace == NULL)
1375 strcpy (own_buf, "E.Btrace not enabled.");
1379 if (strcmp (annex, "all") == 0)
1380 type = btrace_read_all;
1381 else if (strcmp (annex, "new") == 0)
1382 type = btrace_read_new;
1385 strcpy (own_buf, "E.Bad annex.");
1391 buffer_free (&cache);
1393 target_read_btrace (thread->btrace, &cache, type);
1395 else if (offset > cache.used_size)
1397 buffer_free (&cache);
1401 if (len > cache.used_size - offset)
1402 len = cache.used_size - offset;
1404 memcpy (readbuf, cache.buffer + offset, len);
1409 static const struct qxfer qxfer_packets[] =
1411 { "auxv", handle_qxfer_auxv },
1412 { "btrace", handle_qxfer_btrace },
1413 { "fdpic", handle_qxfer_fdpic},
1414 { "features", handle_qxfer_features },
1415 { "libraries", handle_qxfer_libraries },
1416 { "libraries-svr4", handle_qxfer_libraries_svr4 },
1417 { "osdata", handle_qxfer_osdata },
1418 { "siginfo", handle_qxfer_siginfo },
1419 { "spu", handle_qxfer_spu },
1420 { "statictrace", handle_qxfer_statictrace },
1421 { "threads", handle_qxfer_threads },
1422 { "traceframe-info", handle_qxfer_traceframe_info },
1426 handle_qxfer (char *own_buf, int packet_len, int *new_packet_len_p)
1434 if (strncmp (own_buf, "qXfer:", 6) != 0)
1437 /* Grab the object, r/w and annex. */
1438 if (decode_xfer (own_buf + 6, &object, &rw, &annex, &offset) < 0)
1440 write_enn (own_buf);
1445 i < sizeof (qxfer_packets) / sizeof (qxfer_packets[0]);
1448 const struct qxfer *q = &qxfer_packets[i];
1450 if (strcmp (object, q->object) == 0)
1452 if (strcmp (rw, "read") == 0)
1454 unsigned char *data;
1459 /* Grab the offset and length. */
1460 if (decode_xfer_read (offset, &ofs, &len) < 0)
1462 write_enn (own_buf);
1466 /* Read one extra byte, as an indicator of whether there is
1468 if (len > PBUFSIZ - 2)
1470 data = malloc (len + 1);
1473 write_enn (own_buf);
1476 n = (*q->xfer) (annex, data, NULL, ofs, len + 1);
1484 /* Preserve error message. */
1487 write_enn (own_buf);
1489 *new_packet_len_p = write_qxfer_response (own_buf, data, len, 1);
1491 *new_packet_len_p = write_qxfer_response (own_buf, data, n, 0);
1496 else if (strcmp (rw, "write") == 0)
1501 unsigned char *data;
1503 strcpy (own_buf, "E00");
1504 data = malloc (packet_len - (offset - own_buf));
1507 write_enn (own_buf);
1510 if (decode_xfer_write (offset, packet_len - (offset - own_buf),
1511 &ofs, &len, data) < 0)
1514 write_enn (own_buf);
1518 n = (*q->xfer) (annex, NULL, data, ofs, len);
1526 /* Preserve error message. */
1529 write_enn (own_buf);
1531 sprintf (own_buf, "%x", n);
1544 /* Table used by the crc32 function to calcuate the checksum. */
1546 static unsigned int crc32_table[256] =
1549 /* Compute 32 bit CRC from inferior memory.
1551 On success, return 32 bit CRC.
1552 On failure, return (unsigned long long) -1. */
1554 static unsigned long long
1555 crc32 (CORE_ADDR base, int len, unsigned int crc)
1557 if (!crc32_table[1])
1559 /* Initialize the CRC table and the decoding table. */
1563 for (i = 0; i < 256; i++)
1565 for (c = i << 24, j = 8; j > 0; --j)
1566 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
1573 unsigned char byte = 0;
1575 /* Return failure if memory read fails. */
1576 if (read_inferior_memory (base, &byte, 1) != 0)
1577 return (unsigned long long) -1;
1579 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ byte) & 255];
1582 return (unsigned long long) crc;
1585 /* Handle all of the extended 'q' packets. */
1588 handle_query (char *own_buf, int packet_len, int *new_packet_len_p)
1590 static struct inferior_list_entry *thread_ptr;
1592 /* Reply the current thread id. */
1593 if (strcmp ("qC", own_buf) == 0 && !disable_packet_qC)
1596 require_running (own_buf);
1598 if (!ptid_equal (general_thread, null_ptid)
1599 && !ptid_equal (general_thread, minus_one_ptid))
1600 gdb_id = general_thread;
1603 thread_ptr = all_threads.head;
1604 gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
1607 sprintf (own_buf, "QC");
1609 write_ptid (own_buf, gdb_id);
1613 if (strcmp ("qSymbol::", own_buf) == 0)
1615 /* GDB is suggesting new symbols have been loaded. This may
1616 mean a new shared library has been detected as loaded, so
1617 take the opportunity to check if breakpoints we think are
1618 inserted, still are. Note that it isn't guaranteed that
1619 we'll see this when a shared library is loaded, and nor will
1620 we see this for unloads (although breakpoints in unloaded
1621 libraries shouldn't trigger), as GDB may not find symbols for
1622 the library at all. We also re-validate breakpoints when we
1623 see a second GDB breakpoint for the same address, and or when
1624 we access breakpoint shadows. */
1625 validate_breakpoints ();
1627 if (target_supports_tracepoints ())
1628 tracepoint_look_up_symbols ();
1630 if (target_running () && the_target->look_up_symbols != NULL)
1631 (*the_target->look_up_symbols) ();
1633 strcpy (own_buf, "OK");
1637 if (!disable_packet_qfThreadInfo)
1639 if (strcmp ("qfThreadInfo", own_buf) == 0)
1643 require_running (own_buf);
1644 thread_ptr = all_threads.head;
1647 gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
1648 write_ptid (own_buf, gdb_id);
1649 thread_ptr = thread_ptr->next;
1653 if (strcmp ("qsThreadInfo", own_buf) == 0)
1657 require_running (own_buf);
1658 if (thread_ptr != NULL)
1661 gdb_id = thread_to_gdb_id ((struct thread_info *)thread_ptr);
1662 write_ptid (own_buf, gdb_id);
1663 thread_ptr = thread_ptr->next;
1668 sprintf (own_buf, "l");
1674 if (the_target->read_offsets != NULL
1675 && strcmp ("qOffsets", own_buf) == 0)
1677 CORE_ADDR text, data;
1679 require_running (own_buf);
1680 if (the_target->read_offsets (&text, &data))
1681 sprintf (own_buf, "Text=%lX;Data=%lX;Bss=%lX",
1682 (long)text, (long)data, (long)data);
1684 write_enn (own_buf);
1689 /* Protocol features query. */
1690 if (strncmp ("qSupported", own_buf, 10) == 0
1691 && (own_buf[10] == ':' || own_buf[10] == '\0'))
1693 char *p = &own_buf[10];
1694 int gdb_supports_qRelocInsn = 0;
1696 /* Start processing qSupported packet. */
1697 target_process_qsupported (NULL);
1699 /* Process each feature being provided by GDB. The first
1700 feature will follow a ':', and latter features will follow
1704 char **qsupported = NULL;
1708 /* Two passes, to avoid nested strtok calls in
1709 target_process_qsupported. */
1710 for (p = strtok (p + 1, ";");
1712 p = strtok (NULL, ";"))
1715 qsupported = xrealloc (qsupported, count * sizeof (char *));
1716 qsupported[count - 1] = xstrdup (p);
1719 for (i = 0; i < count; i++)
1722 if (strcmp (p, "multiprocess+") == 0)
1724 /* GDB supports and wants multi-process support if
1726 if (target_supports_multi_process ())
1729 else if (strcmp (p, "qRelocInsn+") == 0)
1731 /* GDB supports relocate instruction requests. */
1732 gdb_supports_qRelocInsn = 1;
1735 target_process_qsupported (p);
1744 "PacketSize=%x;QPassSignals+;QProgramSignals+",
1747 if (the_target->qxfer_libraries_svr4 != NULL)
1748 strcat (own_buf, ";qXfer:libraries-svr4:read+"
1749 ";augmented-libraries-svr4-read+");
1752 /* We do not have any hook to indicate whether the non-SVR4 target
1753 backend supports qXfer:libraries:read, so always report it. */
1754 strcat (own_buf, ";qXfer:libraries:read+");
1757 if (the_target->read_auxv != NULL)
1758 strcat (own_buf, ";qXfer:auxv:read+");
1760 if (the_target->qxfer_spu != NULL)
1761 strcat (own_buf, ";qXfer:spu:read+;qXfer:spu:write+");
1763 if (the_target->qxfer_siginfo != NULL)
1764 strcat (own_buf, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
1766 if (the_target->read_loadmap != NULL)
1767 strcat (own_buf, ";qXfer:fdpic:read+");
1769 /* We always report qXfer:features:read, as targets may
1770 install XML files on a subsequent call to arch_setup.
1771 If we reported to GDB on startup that we don't support
1772 qXfer:feature:read at all, we will never be re-queried. */
1773 strcat (own_buf, ";qXfer:features:read+");
1775 if (transport_is_reliable)
1776 strcat (own_buf, ";QStartNoAckMode+");
1778 if (the_target->qxfer_osdata != NULL)
1779 strcat (own_buf, ";qXfer:osdata:read+");
1781 if (target_supports_multi_process ())
1782 strcat (own_buf, ";multiprocess+");
1784 if (target_supports_non_stop ())
1785 strcat (own_buf, ";QNonStop+");
1787 if (target_supports_disable_randomization ())
1788 strcat (own_buf, ";QDisableRandomization+");
1790 strcat (own_buf, ";qXfer:threads:read+");
1792 if (target_supports_tracepoints ())
1794 strcat (own_buf, ";ConditionalTracepoints+");
1795 strcat (own_buf, ";TraceStateVariables+");
1796 strcat (own_buf, ";TracepointSource+");
1797 strcat (own_buf, ";DisconnectedTracing+");
1798 if (gdb_supports_qRelocInsn && target_supports_fast_tracepoints ())
1799 strcat (own_buf, ";FastTracepoints+");
1800 strcat (own_buf, ";StaticTracepoints+");
1801 strcat (own_buf, ";InstallInTrace+");
1802 strcat (own_buf, ";qXfer:statictrace:read+");
1803 strcat (own_buf, ";qXfer:traceframe-info:read+");
1804 strcat (own_buf, ";EnableDisableTracepoints+");
1805 strcat (own_buf, ";QTBuffer:size+");
1806 strcat (own_buf, ";tracenz+");
1809 /* Support target-side breakpoint conditions and commands. */
1810 strcat (own_buf, ";ConditionalBreakpoints+");
1811 strcat (own_buf, ";BreakpointCommands+");
1813 if (target_supports_agent ())
1814 strcat (own_buf, ";QAgent+");
1816 if (target_supports_btrace ())
1818 strcat (own_buf, ";Qbtrace:bts+");
1819 strcat (own_buf, ";Qbtrace:off+");
1820 strcat (own_buf, ";qXfer:btrace:read+");
1826 /* Thread-local storage support. */
1827 if (the_target->get_tls_address != NULL
1828 && strncmp ("qGetTLSAddr:", own_buf, 12) == 0)
1830 char *p = own_buf + 12;
1831 CORE_ADDR parts[2], address = 0;
1833 ptid_t ptid = null_ptid;
1835 require_running (own_buf);
1837 for (i = 0; i < 3; i++)
1845 p2 = strchr (p, ',');
1858 ptid = read_ptid (p, NULL);
1860 decode_address (&parts[i - 1], p, len);
1864 if (p != NULL || i < 3)
1868 struct thread_info *thread = find_thread_ptid (ptid);
1873 err = the_target->get_tls_address (thread, parts[0], parts[1],
1879 strcpy (own_buf, paddress(address));
1884 write_enn (own_buf);
1888 /* Otherwise, pretend we do not understand this packet. */
1891 /* Windows OS Thread Information Block address support. */
1892 if (the_target->get_tib_address != NULL
1893 && strncmp ("qGetTIBAddr:", own_buf, 12) == 0)
1898 ptid_t ptid = read_ptid (own_buf + 12, &annex);
1900 n = (*the_target->get_tib_address) (ptid, &tlb);
1903 strcpy (own_buf, paddress(tlb));
1908 write_enn (own_buf);
1914 /* Handle "monitor" commands. */
1915 if (strncmp ("qRcmd,", own_buf, 6) == 0)
1917 char *mon = malloc (PBUFSIZ);
1918 int len = strlen (own_buf + 6);
1922 write_enn (own_buf);
1926 if ((len % 2) != 0 || unhexify (mon, own_buf + 6, len / 2) != len / 2)
1928 write_enn (own_buf);
1932 mon[len / 2] = '\0';
1936 if (the_target->handle_monitor_command == NULL
1937 || (*the_target->handle_monitor_command) (mon) == 0)
1938 /* Default processing. */
1939 handle_monitor_command (mon, own_buf);
1945 if (strncmp ("qSearch:memory:", own_buf,
1946 sizeof ("qSearch:memory:") - 1) == 0)
1948 require_running (own_buf);
1949 handle_search_memory (own_buf, packet_len);
1953 if (strcmp (own_buf, "qAttached") == 0
1954 || strncmp (own_buf, "qAttached:", sizeof ("qAttached:") - 1) == 0)
1956 struct process_info *process;
1958 if (own_buf[sizeof ("qAttached") - 1])
1960 int pid = strtoul (own_buf + sizeof ("qAttached:") - 1, NULL, 16);
1961 process = (struct process_info *)
1962 find_inferior_id (&all_processes, pid_to_ptid (pid));
1966 require_running (own_buf);
1967 process = current_process ();
1970 if (process == NULL)
1972 write_enn (own_buf);
1976 strcpy (own_buf, process->attached ? "1" : "0");
1980 if (strncmp ("qCRC:", own_buf, 5) == 0)
1982 /* CRC check (compare-section). */
1986 unsigned long long crc;
1988 require_running (own_buf);
1989 comma = unpack_varlen_hex (own_buf + 5, &base);
1990 if (*comma++ != ',')
1992 write_enn (own_buf);
1995 len = strtoul (comma, NULL, 16);
1996 crc = crc32 (base, len, 0xffffffff);
1997 /* Check for memory failure. */
1998 if (crc == (unsigned long long) -1)
2000 write_enn (own_buf);
2003 sprintf (own_buf, "C%lx", (unsigned long) crc);
2007 if (handle_qxfer (own_buf, packet_len, new_packet_len_p))
2010 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf))
2013 /* Otherwise we didn't know what packet it was. Say we didn't
2018 static void gdb_wants_all_threads_stopped (void);
2019 static void resume (struct thread_resume *actions, size_t n);
2021 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
2022 true if CALLBACK returns true. Returns false if no matching thread
2023 is found or CALLBACK results false. */
2026 visit_actioned_threads (const struct thread_resume *actions,
2028 int (*callback) (const struct thread_resume *,
2029 struct thread_info *))
2031 struct inferior_list_entry *entry;
2033 for (entry = all_threads.head; entry != NULL; entry = entry->next)
2037 for (i = 0; i < num_actions; i++)
2039 const struct thread_resume *action = &actions[i];
2041 if (ptid_equal (action->thread, minus_one_ptid)
2042 || ptid_equal (action->thread, entry->id)
2043 || ((ptid_get_pid (action->thread)
2044 == ptid_get_pid (entry->id))
2045 && ptid_get_lwp (action->thread) == -1))
2047 struct thread_info *thread = (struct thread_info *) entry;
2049 if ((*callback) (action, thread))
2058 /* Callback for visit_actioned_threads. If the thread has a pending
2059 status to report, report it now. */
2062 handle_pending_status (const struct thread_resume *resumption,
2063 struct thread_info *thread)
2065 if (thread->status_pending_p)
2067 thread->status_pending_p = 0;
2069 last_status = thread->last_status;
2070 last_ptid = thread->entry.id;
2071 prepare_resume_reply (own_buf, last_ptid, &last_status);
2077 /* Parse vCont packets. */
2079 handle_v_cont (char *own_buf)
2083 struct thread_resume *resume_info;
2084 struct thread_resume default_action = {{0}};
2086 /* Count the number of semicolons in the packet. There should be one
2087 for every action. */
2093 p = strchr (p, ';');
2096 resume_info = malloc (n * sizeof (resume_info[0]));
2097 if (resume_info == NULL)
2105 memset (&resume_info[i], 0, sizeof resume_info[i]);
2107 if (p[0] == 's' || p[0] == 'S')
2108 resume_info[i].kind = resume_step;
2109 else if (p[0] == 'r')
2110 resume_info[i].kind = resume_step;
2111 else if (p[0] == 'c' || p[0] == 'C')
2112 resume_info[i].kind = resume_continue;
2113 else if (p[0] == 't')
2114 resume_info[i].kind = resume_stop;
2118 if (p[0] == 'S' || p[0] == 'C')
2121 sig = strtol (p + 1, &q, 16);
2126 if (!gdb_signal_to_host_p (sig))
2128 resume_info[i].sig = gdb_signal_to_host (sig);
2130 else if (p[0] == 'r')
2134 p = unpack_varlen_hex (p + 1, &addr);
2135 resume_info[i].step_range_start = addr;
2140 p = unpack_varlen_hex (p + 1, &addr);
2141 resume_info[i].step_range_end = addr;
2150 resume_info[i].thread = minus_one_ptid;
2151 default_action = resume_info[i];
2153 /* Note: we don't increment i here, we'll overwrite this entry
2154 the next time through. */
2156 else if (p[0] == ':')
2158 ptid_t ptid = read_ptid (p + 1, &q);
2163 if (p[0] != ';' && p[0] != 0)
2166 resume_info[i].thread = ptid;
2173 resume_info[i] = default_action;
2175 /* `cont_thread' is still used in occasional places in the backend,
2176 to implement single-thread scheduler-locking. Doesn't make sense
2177 to set it if we see a stop request, or a wildcard action (one
2178 with '-1' (all threads), or 'pPID.-1' (all threads of PID)). */
2180 && !(ptid_equal (resume_info[0].thread, minus_one_ptid)
2181 || ptid_get_lwp (resume_info[0].thread) == -1)
2182 && resume_info[0].kind != resume_stop)
2183 cont_thread = resume_info[0].thread;
2185 cont_thread = minus_one_ptid;
2186 set_desired_inferior (0);
2188 resume (resume_info, n);
2193 write_enn (own_buf);
2198 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
2201 resume (struct thread_resume *actions, size_t num_actions)
2205 /* Check if among the threads that GDB wants actioned, there's
2206 one with a pending status to report. If so, skip actually
2207 resuming/stopping and report the pending event
2209 if (visit_actioned_threads (actions, num_actions, handle_pending_status))
2215 (*the_target->resume) (actions, num_actions);
2221 last_ptid = mywait (minus_one_ptid, &last_status, 0, 1);
2223 if (last_status.kind != TARGET_WAITKIND_EXITED
2224 && last_status.kind != TARGET_WAITKIND_SIGNALLED)
2225 current_inferior->last_status = last_status;
2227 /* From the client's perspective, all-stop mode always stops all
2228 threads implicitly (and the target backend has already done
2229 so by now). Tag all threads as "want-stopped", so we don't
2230 resume them implicitly without the client telling us to. */
2231 gdb_wants_all_threads_stopped ();
2232 prepare_resume_reply (own_buf, last_ptid, &last_status);
2233 disable_async_io ();
2235 if (last_status.kind == TARGET_WAITKIND_EXITED
2236 || last_status.kind == TARGET_WAITKIND_SIGNALLED)
2237 mourn_inferior (find_process_pid (ptid_get_pid (last_ptid)));
2241 /* Attach to a new program. Return 1 if successful, 0 if failure. */
2243 handle_v_attach (char *own_buf)
2247 pid = strtol (own_buf + 8, NULL, 16);
2248 if (pid != 0 && attach_inferior (pid) == 0)
2250 /* Don't report shared library events after attaching, even if
2251 some libraries are preloaded. GDB will always poll the
2252 library list. Avoids the "stopped by shared library event"
2253 notice on the GDB side. */
2258 /* In non-stop, we don't send a resume reply. Stop events
2259 will follow up using the normal notification
2264 prepare_resume_reply (own_buf, last_ptid, &last_status);
2270 write_enn (own_buf);
2275 /* Run a new program. Return 1 if successful, 0 if failure. */
2277 handle_v_run (char *own_buf)
2279 char *p, *next_p, **new_argv;
2283 for (p = own_buf + strlen ("vRun;"); p && *p; p = strchr (p, ';'))
2289 new_argv = calloc (new_argc + 2, sizeof (char *));
2290 if (new_argv == NULL)
2292 write_enn (own_buf);
2297 for (p = own_buf + strlen ("vRun;"); *p; p = next_p)
2299 next_p = strchr (p, ';');
2301 next_p = p + strlen (p);
2303 if (i == 0 && p == next_p)
2307 /* FIXME: Fail request if out of memory instead of dying. */
2308 new_argv[i] = xmalloc (1 + (next_p - p) / 2);
2309 unhexify (new_argv[i], p, (next_p - p) / 2);
2310 new_argv[i][(next_p - p) / 2] = '\0';
2319 if (new_argv[0] == NULL)
2321 /* GDB didn't specify a program to run. Use the program from the
2322 last run with the new argument list. */
2324 if (program_argv == NULL)
2326 write_enn (own_buf);
2327 freeargv (new_argv);
2331 new_argv[0] = strdup (program_argv[0]);
2332 if (new_argv[0] == NULL)
2334 write_enn (own_buf);
2335 freeargv (new_argv);
2340 /* Free the old argv and install the new one. */
2341 freeargv (program_argv);
2342 program_argv = new_argv;
2344 start_inferior (program_argv);
2345 if (last_status.kind == TARGET_WAITKIND_STOPPED)
2347 prepare_resume_reply (own_buf, last_ptid, &last_status);
2349 /* In non-stop, sending a resume reply doesn't set the general
2350 thread, but GDB assumes a vRun sets it (this is so GDB can
2351 query which is the main thread of the new inferior. */
2353 general_thread = last_ptid;
2359 write_enn (own_buf);
2364 /* Kill process. Return 1 if successful, 0 if failure. */
2366 handle_v_kill (char *own_buf)
2369 char *p = &own_buf[6];
2371 pid = strtol (p, NULL, 16);
2374 if (pid != 0 && kill_inferior (pid) == 0)
2376 last_status.kind = TARGET_WAITKIND_SIGNALLED;
2377 last_status.value.sig = GDB_SIGNAL_KILL;
2378 last_ptid = pid_to_ptid (pid);
2379 discard_queued_stop_replies (pid);
2385 write_enn (own_buf);
2390 /* Handle all of the extended 'v' packets. */
2392 handle_v_requests (char *own_buf, int packet_len, int *new_packet_len)
2394 if (!disable_packet_vCont)
2396 if (strncmp (own_buf, "vCont;", 6) == 0)
2398 require_running (own_buf);
2399 handle_v_cont (own_buf);
2403 if (strncmp (own_buf, "vCont?", 6) == 0)
2405 strcpy (own_buf, "vCont;c;C;s;S;t");
2406 if (target_supports_range_stepping ())
2408 own_buf = own_buf + strlen (own_buf);
2409 strcpy (own_buf, ";r");
2415 if (strncmp (own_buf, "vFile:", 6) == 0
2416 && handle_vFile (own_buf, packet_len, new_packet_len))
2419 if (strncmp (own_buf, "vAttach;", 8) == 0)
2421 if ((!extended_protocol || !multi_process) && target_running ())
2423 fprintf (stderr, "Already debugging a process\n");
2424 write_enn (own_buf);
2427 handle_v_attach (own_buf);
2431 if (strncmp (own_buf, "vRun;", 5) == 0)
2433 if ((!extended_protocol || !multi_process) && target_running ())
2435 fprintf (stderr, "Already debugging a process\n");
2436 write_enn (own_buf);
2439 handle_v_run (own_buf);
2443 if (strncmp (own_buf, "vKill;", 6) == 0)
2445 if (!target_running ())
2447 fprintf (stderr, "No process to kill\n");
2448 write_enn (own_buf);
2451 handle_v_kill (own_buf);
2455 if (handle_notif_ack (own_buf, packet_len))
2458 /* Otherwise we didn't know what packet it was. Say we didn't
2464 /* Resume inferior and wait for another event. In non-stop mode,
2465 don't really wait here, but return immediatelly to the event
2468 myresume (char *own_buf, int step, int sig)
2470 struct thread_resume resume_info[2];
2472 int valid_cont_thread;
2474 set_desired_inferior (0);
2476 valid_cont_thread = (!ptid_equal (cont_thread, null_ptid)
2477 && !ptid_equal (cont_thread, minus_one_ptid));
2479 if (step || sig || valid_cont_thread)
2481 resume_info[0].thread = current_ptid;
2483 resume_info[0].kind = resume_step;
2485 resume_info[0].kind = resume_continue;
2486 resume_info[0].sig = sig;
2490 if (!valid_cont_thread)
2492 resume_info[n].thread = minus_one_ptid;
2493 resume_info[n].kind = resume_continue;
2494 resume_info[n].sig = 0;
2498 resume (resume_info, n);
2501 /* Callback for for_each_inferior. Make a new stop reply for each
2505 queue_stop_reply_callback (struct inferior_list_entry *entry, void *arg)
2507 struct thread_info *thread = (struct thread_info *) entry;
2509 /* For now, assume targets that don't have this callback also don't
2510 manage the thread's last_status field. */
2511 if (the_target->thread_stopped == NULL)
2513 struct vstop_notif *new_notif = xmalloc (sizeof (*new_notif));
2515 new_notif->ptid = entry->id;
2516 new_notif->status = thread->last_status;
2517 /* Pass the last stop reply back to GDB, but don't notify
2519 notif_event_enque (¬if_stop,
2520 (struct notif_event *) new_notif);
2524 if (thread_stopped (thread))
2529 = target_waitstatus_to_string (&thread->last_status);
2532 "Reporting thread %s as already stopped with %s\n",
2533 target_pid_to_str (entry->id),
2536 xfree (status_string);
2539 gdb_assert (thread->last_status.kind != TARGET_WAITKIND_IGNORE);
2541 /* Pass the last stop reply back to GDB, but don't notify
2543 queue_stop_reply (entry->id, &thread->last_status);
2550 /* Set this inferior threads's state as "want-stopped". We won't
2551 resume this thread until the client gives us another action for
2555 gdb_wants_thread_stopped (struct inferior_list_entry *entry)
2557 struct thread_info *thread = (struct thread_info *) entry;
2559 thread->last_resume_kind = resume_stop;
2561 if (thread->last_status.kind == TARGET_WAITKIND_IGNORE)
2563 /* Most threads are stopped implicitly (all-stop); tag that with
2565 thread->last_status.kind = TARGET_WAITKIND_STOPPED;
2566 thread->last_status.value.sig = GDB_SIGNAL_0;
2570 /* Set all threads' states as "want-stopped". */
2573 gdb_wants_all_threads_stopped (void)
2575 for_each_inferior (&all_threads, gdb_wants_thread_stopped);
2578 /* Clear the gdb_detached flag of every process. */
2581 gdb_reattached_process (struct inferior_list_entry *entry)
2583 struct process_info *process = (struct process_info *) entry;
2585 process->gdb_detached = 0;
2588 /* Callback for for_each_inferior. Clear the thread's pending status
2592 clear_pending_status_callback (struct inferior_list_entry *entry)
2594 struct thread_info *thread = (struct thread_info *) entry;
2596 thread->status_pending_p = 0;
2599 /* Callback for for_each_inferior. If the thread is stopped with an
2600 interesting event, mark it as having a pending event. */
2603 set_pending_status_callback (struct inferior_list_entry *entry)
2605 struct thread_info *thread = (struct thread_info *) entry;
2607 if (thread->last_status.kind != TARGET_WAITKIND_STOPPED
2608 || (thread->last_status.value.sig != GDB_SIGNAL_0
2609 /* A breakpoint, watchpoint or finished step from a previous
2610 GDB run isn't considered interesting for a new GDB run.
2611 If we left those pending, the new GDB could consider them
2612 random SIGTRAPs. This leaves out real async traps. We'd
2613 have to peek into the (target-specific) siginfo to
2614 distinguish those. */
2615 && thread->last_status.value.sig != GDB_SIGNAL_TRAP))
2616 thread->status_pending_p = 1;
2619 /* Callback for find_inferior. Return true if ENTRY (a thread) has a
2620 pending status to report to GDB. */
2623 find_status_pending_thread_callback (struct inferior_list_entry *entry, void *data)
2625 struct thread_info *thread = (struct thread_info *) entry;
2627 return thread->status_pending_p;
2630 /* Status handler for the '?' packet. */
2633 handle_status (char *own_buf)
2635 /* GDB is connected, don't forward events to the target anymore. */
2636 for_each_inferior (&all_processes, gdb_reattached_process);
2638 discard_queued_stop_replies (-1);
2639 for_each_inferior (&all_threads, clear_pending_status_callback);
2641 /* In non-stop mode, we must send a stop reply for each stopped
2642 thread. In all-stop mode, just send one for the first stopped
2647 find_inferior (&all_threads, queue_stop_reply_callback, NULL);
2649 /* The first is sent immediatly. OK is sent if there is no
2650 stopped thread, which is the same handling of the vStopped
2651 packet (by design). */
2652 notif_write_event (¬if_stop, own_buf);
2656 struct inferior_list_entry *thread = NULL;
2659 stabilize_threads ();
2660 gdb_wants_all_threads_stopped ();
2662 /* We can only report one status, but we might be coming out of
2663 non-stop -- if more than one thread is stopped with
2664 interesting events, leave events for the threads we're not
2665 reporting now pending. They'll be reported the next time the
2666 threads are resumed. Start by marking all interesting events
2668 for_each_inferior (&all_threads, set_pending_status_callback);
2670 /* Prefer the last thread that reported an event to GDB (even if
2671 that was a GDB_SIGNAL_TRAP). */
2672 if (last_status.kind != TARGET_WAITKIND_IGNORE
2673 && last_status.kind != TARGET_WAITKIND_EXITED
2674 && last_status.kind != TARGET_WAITKIND_SIGNALLED)
2675 thread = find_inferior_id (&all_threads, last_ptid);
2677 /* If the last event thread is not found for some reason, look
2678 for some other thread that might have an event to report. */
2680 thread = find_inferior (&all_threads,
2681 find_status_pending_thread_callback, NULL);
2683 /* If we're still out of luck, simply pick the first thread in
2686 thread = all_threads.head;
2690 struct thread_info *tp = (struct thread_info *) thread;
2692 /* We're reporting this event, so it's no longer
2694 tp->status_pending_p = 0;
2696 /* GDB assumes the current thread is the thread we're
2697 reporting the status for. */
2698 general_thread = thread->id;
2699 set_desired_inferior (1);
2701 gdb_assert (tp->last_status.kind != TARGET_WAITKIND_IGNORE);
2702 prepare_resume_reply (own_buf, tp->entry.id, &tp->last_status);
2705 strcpy (own_buf, "W00");
2710 gdbserver_version (void)
2712 printf ("GNU gdbserver %s%s\n"
2713 "Copyright (C) 2014 Free Software Foundation, Inc.\n"
2714 "gdbserver is free software, covered by the "
2715 "GNU General Public License.\n"
2716 "This gdbserver was configured as \"%s\"\n",
2717 PKGVERSION, version, host_name);
2721 gdbserver_usage (FILE *stream)
2723 fprintf (stream, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
2724 "\tgdbserver [OPTIONS] --attach COMM PID\n"
2725 "\tgdbserver [OPTIONS] --multi COMM\n"
2727 "COMM may either be a tty device (for serial debugging), or \n"
2728 "HOST:PORT to listen for a TCP connection.\n"
2731 " --debug Enable general debugging output.\n"
2732 " --remote-debug Enable remote protocol debugging output.\n"
2733 " --version Display version information and exit.\n"
2734 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
2735 " --once Exit after the first connection has "
2737 if (REPORT_BUGS_TO[0] && stream == stdout)
2738 fprintf (stream, "Report bugs to \"%s\".\n", REPORT_BUGS_TO);
2742 gdbserver_show_disableable (FILE *stream)
2744 fprintf (stream, "Disableable packets:\n"
2745 " vCont \tAll vCont packets\n"
2746 " qC \tQuerying the current thread\n"
2747 " qfThreadInfo\tThread listing\n"
2748 " Tthread \tPassing the thread specifier in the "
2749 "T stop reply packet\n"
2750 " threads \tAll of the above\n");
2754 #undef require_running
2755 #define require_running(BUF) \
2756 if (!target_running ()) \
2763 first_thread_of (struct inferior_list_entry *entry, void *args)
2765 int pid = * (int *) args;
2767 if (ptid_get_pid (entry->id) == pid)
2774 kill_inferior_callback (struct inferior_list_entry *entry)
2776 struct process_info *process = (struct process_info *) entry;
2777 int pid = ptid_get_pid (process->head.id);
2779 kill_inferior (pid);
2780 discard_queued_stop_replies (pid);
2783 /* Callback for for_each_inferior to detach or kill the inferior,
2784 depending on whether we attached to it or not.
2785 We inform the user whether we're detaching or killing the process
2786 as this is only called when gdbserver is about to exit. */
2789 detach_or_kill_inferior_callback (struct inferior_list_entry *entry)
2791 struct process_info *process = (struct process_info *) entry;
2792 int pid = ptid_get_pid (process->head.id);
2794 if (process->attached)
2795 detach_inferior (pid);
2797 kill_inferior (pid);
2799 discard_queued_stop_replies (pid);
2802 /* for_each_inferior callback for detach_or_kill_for_exit to print
2803 the pids of started inferiors. */
2806 print_started_pid (struct inferior_list_entry *entry)
2808 struct process_info *process = (struct process_info *) entry;
2810 if (! process->attached)
2812 int pid = ptid_get_pid (process->head.id);
2813 fprintf (stderr, " %d", pid);
2817 /* for_each_inferior callback for detach_or_kill_for_exit to print
2818 the pids of attached inferiors. */
2821 print_attached_pid (struct inferior_list_entry *entry)
2823 struct process_info *process = (struct process_info *) entry;
2825 if (process->attached)
2827 int pid = ptid_get_pid (process->head.id);
2828 fprintf (stderr, " %d", pid);
2832 /* Call this when exiting gdbserver with possible inferiors that need
2833 to be killed or detached from. */
2836 detach_or_kill_for_exit (void)
2838 /* First print a list of the inferiors we will be killing/detaching.
2839 This is to assist the user, for example, in case the inferior unexpectedly
2840 dies after we exit: did we screw up or did the inferior exit on its own?
2841 Having this info will save some head-scratching. */
2843 if (have_started_inferiors_p ())
2845 fprintf (stderr, "Killing process(es):");
2846 for_each_inferior (&all_processes, print_started_pid);
2847 fprintf (stderr, "\n");
2849 if (have_attached_inferiors_p ())
2851 fprintf (stderr, "Detaching process(es):");
2852 for_each_inferior (&all_processes, print_attached_pid);
2853 fprintf (stderr, "\n");
2856 /* Now we can kill or detach the inferiors. */
2858 for_each_inferior (&all_processes, detach_or_kill_inferior_callback);
2862 main (int argc, char *argv[])
2866 char *arg_end, *port;
2867 char **next_arg = &argv[1];
2868 volatile int multi_mode = 0;
2869 volatile int attach = 0;
2872 while (*next_arg != NULL && **next_arg == '-')
2874 if (strcmp (*next_arg, "--version") == 0)
2876 gdbserver_version ();
2879 else if (strcmp (*next_arg, "--help") == 0)
2881 gdbserver_usage (stdout);
2884 else if (strcmp (*next_arg, "--attach") == 0)
2886 else if (strcmp (*next_arg, "--multi") == 0)
2888 else if (strcmp (*next_arg, "--wrapper") == 0)
2892 wrapper_argv = next_arg;
2893 while (*next_arg != NULL && strcmp (*next_arg, "--") != 0)
2896 if (next_arg == wrapper_argv || *next_arg == NULL)
2898 gdbserver_usage (stderr);
2902 /* Consume the "--". */
2905 else if (strcmp (*next_arg, "--debug") == 0)
2907 else if (strcmp (*next_arg, "--remote-debug") == 0)
2909 else if (strcmp (*next_arg, "--disable-packet") == 0)
2911 gdbserver_show_disableable (stdout);
2914 else if (strncmp (*next_arg,
2915 "--disable-packet=",
2916 sizeof ("--disable-packet=") - 1) == 0)
2918 char *packets, *tok;
2920 packets = *next_arg += sizeof ("--disable-packet=") - 1;
2921 for (tok = strtok (packets, ",");
2923 tok = strtok (NULL, ","))
2925 if (strcmp ("vCont", tok) == 0)
2926 disable_packet_vCont = 1;
2927 else if (strcmp ("Tthread", tok) == 0)
2928 disable_packet_Tthread = 1;
2929 else if (strcmp ("qC", tok) == 0)
2930 disable_packet_qC = 1;
2931 else if (strcmp ("qfThreadInfo", tok) == 0)
2932 disable_packet_qfThreadInfo = 1;
2933 else if (strcmp ("threads", tok) == 0)
2935 disable_packet_vCont = 1;
2936 disable_packet_Tthread = 1;
2937 disable_packet_qC = 1;
2938 disable_packet_qfThreadInfo = 1;
2942 fprintf (stderr, "Don't know how to disable \"%s\".\n\n",
2944 gdbserver_show_disableable (stderr);
2949 else if (strcmp (*next_arg, "-") == 0)
2951 /* "-" specifies a stdio connection and is a form of port
2953 *next_arg = STDIO_CONNECTION_NAME;
2956 else if (strcmp (*next_arg, "--disable-randomization") == 0)
2957 disable_randomization = 1;
2958 else if (strcmp (*next_arg, "--no-disable-randomization") == 0)
2959 disable_randomization = 0;
2960 else if (strcmp (*next_arg, "--once") == 0)
2964 fprintf (stderr, "Unknown argument: %s\n", *next_arg);
2972 if (setjmp (toplevel))
2974 fprintf (stderr, "Exiting\n");
2980 if (port == NULL || (!attach && !multi_mode && *next_arg == NULL))
2982 gdbserver_usage (stderr);
2986 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
2987 opened by remote_prepare. */
2990 /* We need to know whether the remote connection is stdio before
2991 starting the inferior. Inferiors created in this scenario have
2992 stdin,stdout redirected. So do this here before we call
2994 remote_prepare (port);
2999 /* --attach used to come after PORT, so allow it there for
3001 if (*next_arg != NULL && strcmp (*next_arg, "--attach") == 0)
3008 && (*next_arg == NULL
3009 || (*next_arg)[0] == '\0'
3010 || (pid = strtoul (*next_arg, &arg_end, 0)) == 0
3012 || next_arg[1] != NULL))
3017 gdbserver_usage (stderr);
3021 initialize_async_io ();
3023 initialize_event_loop ();
3024 if (target_supports_tracepoints ())
3025 initialize_tracepoint ();
3027 own_buf = xmalloc (PBUFSIZ + 1);
3028 mem_buf = xmalloc (PBUFSIZ);
3030 if (pid == 0 && *next_arg != NULL)
3034 n = argc - (next_arg - argv);
3035 program_argv = xmalloc (sizeof (char *) * (n + 1));
3036 for (i = 0; i < n; i++)
3037 program_argv[i] = xstrdup (next_arg[i]);
3038 program_argv[i] = NULL;
3040 /* Wait till we are at first instruction in program. */
3041 start_inferior (program_argv);
3043 /* We are now (hopefully) stopped at the first instruction of
3044 the target process. This assumes that the target process was
3045 successfully created. */
3049 if (attach_inferior (pid) == -1)
3050 error ("Attaching not supported on this target");
3052 /* Otherwise succeeded. */
3056 last_status.kind = TARGET_WAITKIND_EXITED;
3057 last_status.value.integer = 0;
3058 last_ptid = minus_one_ptid;
3061 initialize_notif ();
3063 /* Don't report shared library events on the initial connection,
3064 even if some libraries are preloaded. Avoids the "stopped by
3065 shared library event" notice on gdb side. */
3068 if (setjmp (toplevel))
3070 /* If something fails and longjmps while detaching or killing
3071 inferiors, we'd end up here again, stuck in an infinite loop
3072 trap. Be sure that if that happens, we exit immediately
3074 if (setjmp (toplevel) == 0)
3075 detach_or_kill_for_exit ();
3077 fprintf (stderr, "Detach or kill failed. Exiting\n");
3081 if (last_status.kind == TARGET_WAITKIND_EXITED
3082 || last_status.kind == TARGET_WAITKIND_SIGNALLED)
3087 if (!was_running && !multi_mode)
3089 fprintf (stderr, "No program to debug. GDBserver exiting.\n");
3097 /* Be sure we're out of tfind mode. */
3098 current_traceframe = -1;
3102 if (setjmp (toplevel) != 0)
3104 /* An error occurred. */
3105 if (response_needed)
3107 write_enn (own_buf);
3112 /* Wait for events. This will return when all event sources are
3113 removed from the event loop. */
3114 start_event_loop ();
3116 /* If an exit was requested (using the "monitor exit" command),
3117 terminate now. The only other way to get here is for
3118 getpkt to fail; close the connection and reopen it at the
3121 if (exit_requested || run_once)
3123 /* If something fails and longjmps while detaching or
3124 killing inferiors, we'd end up here again, stuck in an
3125 infinite loop trap. Be sure that if that happens, we
3126 exit immediately instead. */
3127 if (setjmp (toplevel) == 0)
3129 detach_or_kill_for_exit ();
3134 fprintf (stderr, "Detach or kill failed. Exiting\n");
3140 "Remote side has terminated connection. "
3141 "GDBserver will reopen the connection.\n");
3145 if (disconnected_tracing)
3147 /* Try to enable non-stop/async mode, so we we can both
3148 wait for an async socket accept, and handle async
3149 target events simultaneously. There's also no point
3150 either in having the target always stop all threads,
3151 when we're going to pass signals down without
3155 if (start_non_stop (1))
3158 /* Detaching implicitly resumes all threads; simply
3159 disconnecting does not. */
3165 "Disconnected tracing disabled; stopping trace run.\n");
3172 /* Process options coming from Z packets for *point at address
3173 POINT_ADDR. PACKET is the packet buffer. *PACKET is updated
3174 to point to the first char after the last processed option. */
3177 process_point_options (CORE_ADDR point_addr, char **packet)
3179 char *dataptr = *packet;
3182 /* Check if data has the correct format. */
3183 if (*dataptr != ';')
3190 if (*dataptr == ';')
3193 if (*dataptr == 'X')
3195 /* Conditional expression. */
3197 fprintf (stderr, "Found breakpoint condition.\n");
3198 add_breakpoint_condition (point_addr, &dataptr);
3200 else if (strncmp (dataptr, "cmds:", strlen ("cmds:")) == 0)
3202 dataptr += strlen ("cmds:");
3204 fprintf (stderr, "Found breakpoint commands %s.\n", dataptr);
3205 persist = (*dataptr == '1');
3207 add_breakpoint_commands (point_addr, &dataptr, persist);
3211 fprintf (stderr, "Unknown token %c, ignoring.\n",
3213 /* Skip tokens until we find one that we recognize. */
3214 while (*dataptr && *dataptr != ';')
3221 /* Event loop callback that handles a serial event. The first byte in
3222 the serial buffer gets us here. We expect characters to arrive at
3223 a brisk pace, so we read the rest of the packet with a blocking
3227 process_serial_event (void)
3238 int new_packet_len = -1;
3240 /* Used to decide when gdbserver should exit in
3241 multi-mode/remote. */
3242 static int have_ran = 0;
3245 have_ran = target_running ();
3247 disable_async_io ();
3249 response_needed = 0;
3250 packet_len = getpkt (own_buf);
3251 if (packet_len <= 0)
3254 /* Force an event loop break. */
3257 response_needed = 1;
3264 handle_query (own_buf, packet_len, &new_packet_len);
3267 handle_general_set (own_buf);
3270 require_running (own_buf);
3275 pid = strtol (&own_buf[i], NULL, 16);
3278 pid = ptid_get_pid (current_ptid);
3280 if ((tracing && disconnected_tracing) || any_persistent_commands ())
3282 struct thread_resume resume_info;
3283 struct process_info *process = find_process_pid (pid);
3285 if (process == NULL)
3287 write_enn (own_buf);
3291 if (tracing && disconnected_tracing)
3293 "Disconnected tracing in effect, "
3294 "leaving gdbserver attached to the process\n");
3296 if (any_persistent_commands ())
3298 "Persistent commands are present, "
3299 "leaving gdbserver attached to the process\n");
3301 /* Make sure we're in non-stop/async mode, so we we can both
3302 wait for an async socket accept, and handle async target
3303 events simultaneously. There's also no point either in
3304 having the target stop all threads, when we're going to
3305 pass signals down without informing GDB. */
3309 fprintf (stderr, "Forcing non-stop mode\n");
3315 process->gdb_detached = 1;
3317 /* Detaching implicitly resumes all threads. */
3318 resume_info.thread = minus_one_ptid;
3319 resume_info.kind = resume_continue;
3320 resume_info.sig = 0;
3321 (*the_target->resume) (&resume_info, 1);
3324 break; /* from switch/case */
3327 fprintf (stderr, "Detaching from process %d\n", pid);
3329 if (detach_inferior (pid) != 0)
3330 write_enn (own_buf);
3333 discard_queued_stop_replies (pid);
3336 if (extended_protocol)
3338 /* Treat this like a normal program exit. */
3339 last_status.kind = TARGET_WAITKIND_EXITED;
3340 last_status.value.integer = 0;
3341 last_ptid = pid_to_ptid (pid);
3343 current_inferior = NULL;
3350 /* If we are attached, then we can exit. Otherwise, we
3351 need to hang around doing nothing, until the child is
3353 join_inferior (pid);
3359 extended_protocol = 1;
3363 handle_status (own_buf);
3366 if (own_buf[1] == 'c' || own_buf[1] == 'g' || own_buf[1] == 's')
3368 ptid_t gdb_id, thread_id;
3371 require_running (own_buf);
3373 gdb_id = read_ptid (&own_buf[2], NULL);
3375 pid = ptid_get_pid (gdb_id);
3377 if (ptid_equal (gdb_id, null_ptid)
3378 || ptid_equal (gdb_id, minus_one_ptid))
3379 thread_id = null_ptid;
3381 && ptid_equal (pid_to_ptid (pid),
3384 struct thread_info *thread =
3385 (struct thread_info *) find_inferior (&all_threads,
3390 write_enn (own_buf);
3394 thread_id = ((struct inferior_list_entry *)thread)->id;
3398 thread_id = gdb_id_to_thread_id (gdb_id);
3399 if (ptid_equal (thread_id, null_ptid))
3401 write_enn (own_buf);
3406 if (own_buf[1] == 'g')
3408 if (ptid_equal (thread_id, null_ptid))
3410 /* GDB is telling us to choose any thread. Check if
3411 the currently selected thread is still valid. If
3412 it is not, select the first available. */
3413 struct thread_info *thread =
3414 (struct thread_info *) find_inferior_id (&all_threads,
3417 thread_id = all_threads.head->id;
3420 general_thread = thread_id;
3421 set_desired_inferior (1);
3423 else if (own_buf[1] == 'c')
3424 cont_thread = thread_id;
3430 /* Silently ignore it so that gdb can extend the protocol
3431 without compatibility headaches. */
3436 require_running (own_buf);
3437 if (current_traceframe >= 0)
3439 struct regcache *regcache
3440 = new_register_cache (current_target_desc ());
3442 if (fetch_traceframe_registers (current_traceframe,
3444 registers_to_string (regcache, own_buf);
3446 write_enn (own_buf);
3447 free_register_cache (regcache);
3451 struct regcache *regcache;
3453 set_desired_inferior (1);
3454 regcache = get_thread_regcache (current_inferior, 1);
3455 registers_to_string (regcache, own_buf);
3459 require_running (own_buf);
3460 if (current_traceframe >= 0)
3461 write_enn (own_buf);
3464 struct regcache *regcache;
3466 set_desired_inferior (1);
3467 regcache = get_thread_regcache (current_inferior, 1);
3468 registers_from_string (regcache, &own_buf[1]);
3473 require_running (own_buf);
3474 decode_m_packet (&own_buf[1], &mem_addr, &len);
3475 res = gdb_read_memory (mem_addr, mem_buf, len);
3477 write_enn (own_buf);
3479 convert_int_to_ascii (mem_buf, own_buf, res);
3482 require_running (own_buf);
3483 decode_M_packet (&own_buf[1], &mem_addr, &len, &mem_buf);
3484 if (gdb_write_memory (mem_addr, mem_buf, len) == 0)
3487 write_enn (own_buf);
3490 require_running (own_buf);
3491 if (decode_X_packet (&own_buf[1], packet_len - 1,
3492 &mem_addr, &len, &mem_buf) < 0
3493 || gdb_write_memory (mem_addr, mem_buf, len) != 0)
3494 write_enn (own_buf);
3499 require_running (own_buf);
3500 convert_ascii_to_int (own_buf + 1, &sig, 1);
3501 if (gdb_signal_to_host_p (sig))
3502 signal = gdb_signal_to_host (sig);
3505 myresume (own_buf, 0, signal);
3508 require_running (own_buf);
3509 convert_ascii_to_int (own_buf + 1, &sig, 1);
3510 if (gdb_signal_to_host_p (sig))
3511 signal = gdb_signal_to_host (sig);
3514 myresume (own_buf, 1, signal);
3517 require_running (own_buf);
3519 myresume (own_buf, 0, signal);
3522 require_running (own_buf);
3524 myresume (own_buf, 1, signal);
3526 case 'Z': /* insert_ ... */
3528 case 'z': /* remove_ ... */
3533 char type = own_buf[1];
3535 const int insert = ch == 'Z';
3536 char *p = &own_buf[3];
3538 p = unpack_varlen_hex (p, &addr);
3539 len = strtol (p + 1, &dataptr, 16);
3541 /* Default to unrecognized/unsupported. */
3545 case '0': /* software-breakpoint */
3546 case '1': /* hardware-breakpoint */
3547 case '2': /* write watchpoint */
3548 case '3': /* read watchpoint */
3549 case '4': /* access watchpoint */
3550 require_running (own_buf);
3551 if (insert && the_target->insert_point != NULL)
3553 /* Insert the breakpoint. If it is already inserted, nothing
3555 res = (*the_target->insert_point) (type, addr, len);
3557 /* GDB may have sent us a list of *point parameters to be
3558 evaluated on the target's side. Read such list here. If we
3559 already have a list of parameters, GDB is telling us to drop
3560 that list and use this one instead. */
3561 if (!res && (type == '0' || type == '1'))
3563 /* Remove previous conditions. */
3564 clear_gdb_breakpoint_conditions (addr);
3565 process_point_options (addr, &dataptr);
3568 else if (!insert && the_target->remove_point != NULL)
3569 res = (*the_target->remove_point) (type, addr, len);
3581 write_enn (own_buf);
3585 response_needed = 0;
3586 if (!target_running ())
3587 /* The packet we received doesn't make sense - but we can't
3588 reply to it, either. */
3591 fprintf (stderr, "Killing all inferiors\n");
3592 for_each_inferior (&all_processes, kill_inferior_callback);
3594 /* When using the extended protocol, we wait with no program
3595 running. The traditional protocol will exit instead. */
3596 if (extended_protocol)
3598 last_status.kind = TARGET_WAITKIND_EXITED;
3599 last_status.value.sig = GDB_SIGNAL_KILL;
3607 ptid_t gdb_id, thread_id;
3609 require_running (own_buf);
3611 gdb_id = read_ptid (&own_buf[1], NULL);
3612 thread_id = gdb_id_to_thread_id (gdb_id);
3613 if (ptid_equal (thread_id, null_ptid))
3615 write_enn (own_buf);
3619 if (mythread_alive (thread_id))
3622 write_enn (own_buf);
3626 response_needed = 0;
3628 /* Restarting the inferior is only supported in the extended
3630 if (extended_protocol)
3632 if (target_running ())
3633 for_each_inferior (&all_processes,
3634 kill_inferior_callback);
3635 fprintf (stderr, "GDBserver restarting\n");
3637 /* Wait till we are at 1st instruction in prog. */
3638 if (program_argv != NULL)
3639 start_inferior (program_argv);
3642 last_status.kind = TARGET_WAITKIND_EXITED;
3643 last_status.value.sig = GDB_SIGNAL_KILL;
3649 /* It is a request we don't understand. Respond with an
3650 empty packet so that gdb knows that we don't support this
3656 /* Extended (long) request. */
3657 handle_v_requests (own_buf, packet_len, &new_packet_len);
3661 /* It is a request we don't understand. Respond with an empty
3662 packet so that gdb knows that we don't support this
3668 if (new_packet_len != -1)
3669 putpkt_binary (own_buf, new_packet_len);
3673 response_needed = 0;
3675 if (!extended_protocol && have_ran && !target_running ())
3677 /* In non-stop, defer exiting until GDB had a chance to query
3678 the whole vStopped list (until it gets an OK). */
3679 if (QUEUE_is_empty (notif_event_p, notif_stop.queue))
3681 /* Be transparent when GDB is connected through stdio -- no
3682 need to spam GDB's console. */
3683 if (!remote_connection_is_stdio ())
3684 fprintf (stderr, "GDBserver exiting\n");
3696 /* Event-loop callback for serial events. */
3699 handle_serial_event (int err, gdb_client_data client_data)
3702 fprintf (stderr, "handling possible serial event\n");
3704 /* Really handle it. */
3705 if (process_serial_event () < 0)
3708 /* Be sure to not change the selected inferior behind GDB's back.
3709 Important in the non-stop mode asynchronous protocol. */
3710 set_desired_inferior (1);
3715 /* Event-loop callback for target events. */
3718 handle_target_event (int err, gdb_client_data client_data)
3721 fprintf (stderr, "handling possible target event\n");
3723 last_ptid = mywait (minus_one_ptid, &last_status,
3726 if (last_status.kind != TARGET_WAITKIND_IGNORE)
3728 int pid = ptid_get_pid (last_ptid);
3729 struct process_info *process = find_process_pid (pid);
3730 int forward_event = !gdb_connected () || process->gdb_detached;
3732 if (last_status.kind == TARGET_WAITKIND_EXITED
3733 || last_status.kind == TARGET_WAITKIND_SIGNALLED)
3735 mark_breakpoints_out (process);
3736 mourn_inferior (process);
3740 /* We're reporting this thread as stopped. Update its
3741 "want-stopped" state to what the client wants, until it
3742 gets a new resume action. */
3743 current_inferior->last_resume_kind = resume_stop;
3744 current_inferior->last_status = last_status;
3749 if (!target_running ())
3751 /* The last process exited. We're done. */
3755 if (last_status.kind == TARGET_WAITKIND_STOPPED)
3757 /* A thread stopped with a signal, but gdb isn't
3758 connected to handle it. Pass it down to the
3759 inferior, as if it wasn't being traced. */
3760 struct thread_resume resume_info;
3764 "GDB not connected; forwarding event %d for [%s]\n",
3765 (int) last_status.kind,
3766 target_pid_to_str (last_ptid));
3768 resume_info.thread = last_ptid;
3769 resume_info.kind = resume_continue;
3770 resume_info.sig = gdb_signal_to_host (last_status.value.sig);
3771 (*the_target->resume) (&resume_info, 1);
3773 else if (debug_threads)
3774 fprintf (stderr, "GDB not connected; ignoring event %d for [%s]\n",
3775 (int) last_status.kind,
3776 target_pid_to_str (last_ptid));
3780 struct vstop_notif *vstop_notif
3781 = xmalloc (sizeof (struct vstop_notif));
3783 vstop_notif->status = last_status;
3784 vstop_notif->ptid = last_ptid;
3785 /* Push Stop notification. */
3786 notif_push (¬if_stop,
3787 (struct notif_event *) vstop_notif);
3791 /* Be sure to not change the selected inferior behind GDB's back.
3792 Important in the non-stop mode asynchronous protocol. */
3793 set_desired_inferior (1);