1 /* Main code for remote server for GDB.
2 Copyright (C) 1989-2020 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"
21 #include "gdbsupport/agent.h"
24 #include "gdbsupport/rsp-low.h"
25 #include "gdbsupport/signals-state-save-restore.h"
31 #include "gdbsupport/gdb_vecs.h"
32 #include "gdbsupport/gdb_wait.h"
33 #include "gdbsupport/btrace-common.h"
34 #include "gdbsupport/filestuff.h"
35 #include "tracepoint.h"
39 #include "gdbsupport/common-inferior.h"
40 #include "gdbsupport/job-control.h"
41 #include "gdbsupport/environ.h"
42 #include "filenames.h"
43 #include "gdbsupport/pathstuff.h"
45 #include "xml-builtin.h"
48 #include "gdbsupport/selftest.h"
49 #include "gdbsupport/scope-exit.h"
50 #include "gdbsupport/gdb_select.h"
51 #include "gdbsupport/scoped_restore.h"
52 #include "gdbsupport/search.h"
54 #define require_running_or_return(BUF) \
55 if (!target_running ()) \
61 #define require_running_or_break(BUF) \
62 if (!target_running ()) \
68 /* String containing the current directory (what getwd would return). */
70 char *current_directory
;
72 /* The environment to pass to the inferior when creating it. */
74 static gdb_environ our_environ
;
78 static bool extended_protocol
;
79 static bool response_needed
;
80 static bool exit_requested
;
82 /* --once: Exit after the first connection has closed. */
85 /* Whether to report TARGET_WAITKIND_NO_RESUMED events. */
86 static bool report_no_resumed
;
88 /* The event loop checks this to decide whether to continue accepting
90 static bool keep_processing_events
= true;
95 /* Set the PROGRAM_PATH. Here we adjust the path of the provided
97 void set (gdb::unique_xmalloc_ptr
<char> &&path
)
99 m_path
= std::move (path
);
101 /* Make sure we're using the absolute path of the inferior when
103 if (!contains_dir_separator (m_path
.get ()))
107 /* Check if the file is in our CWD. If it is, then we prefix
108 its name with CURRENT_DIRECTORY. Otherwise, we leave the
109 name as-is because we'll try searching for it in $PATH. */
110 if (is_regular_file (m_path
.get (), ®_file_errno
))
111 m_path
= gdb_abspath (m_path
.get ());
115 /* Return the PROGRAM_PATH. */
117 { return m_path
.get (); }
120 /* The program name, adjusted if needed. */
121 gdb::unique_xmalloc_ptr
<char> m_path
;
123 static std::vector
<char *> program_args
;
124 static std::string wrapper_argv
;
126 /* The PID of the originally created or attached inferior. Used to
127 send signals to the process when GDB sends us an asynchronous interrupt
128 (user hitting Control-C in the client), and to wait for the child to exit
129 when no longer debugging it. */
131 unsigned long signal_pid
;
133 /* Set if you want to disable optional thread related packets support
134 in gdbserver, for the sake of testing GDB against stubs that don't
136 bool disable_packet_vCont
;
137 bool disable_packet_Tthread
;
138 bool disable_packet_qC
;
139 bool disable_packet_qfThreadInfo
;
140 bool disable_packet_T
;
142 static unsigned char *mem_buf
;
144 /* A sub-class of 'struct notif_event' for stop, holding information
145 relative to a single stop reply. We keep a queue of these to
146 push to GDB in non-stop mode. */
148 struct vstop_notif
: public notif_event
150 /* Thread or process that got the event. */
154 struct target_waitstatus status
;
157 /* The current btrace configuration. This is gdbserver's mirror of GDB's
158 btrace configuration. */
159 static struct btrace_config current_btrace_conf
;
161 /* The client remote protocol state. */
163 static client_state g_client_state
;
168 client_state
&cs
= g_client_state
;
173 /* Put a stop reply to the stop reply queue. */
176 queue_stop_reply (ptid_t ptid
, struct target_waitstatus
*status
)
178 struct vstop_notif
*new_notif
= new struct vstop_notif
;
180 new_notif
->ptid
= ptid
;
181 new_notif
->status
= *status
;
183 notif_event_enque (¬if_stop
, new_notif
);
187 remove_all_on_match_ptid (struct notif_event
*event
, ptid_t filter_ptid
)
189 struct vstop_notif
*vstop_event
= (struct vstop_notif
*) event
;
191 return vstop_event
->ptid
.matches (filter_ptid
);
197 discard_queued_stop_replies (ptid_t ptid
)
199 std::list
<notif_event
*>::iterator iter
, next
, end
;
200 end
= notif_stop
.queue
.end ();
201 for (iter
= notif_stop
.queue
.begin (); iter
!= end
; iter
= next
)
206 if (remove_all_on_match_ptid (*iter
, ptid
))
209 notif_stop
.queue
.erase (iter
);
215 vstop_notif_reply (struct notif_event
*event
, char *own_buf
)
217 struct vstop_notif
*vstop
= (struct vstop_notif
*) event
;
219 prepare_resume_reply (own_buf
, vstop
->ptid
, &vstop
->status
);
222 /* Helper for in_queued_stop_replies. */
225 in_queued_stop_replies_ptid (struct notif_event
*event
, ptid_t filter_ptid
)
227 struct vstop_notif
*vstop_event
= (struct vstop_notif
*) event
;
229 if (vstop_event
->ptid
.matches (filter_ptid
))
232 /* Don't resume fork children that GDB does not know about yet. */
233 if ((vstop_event
->status
.kind
== TARGET_WAITKIND_FORKED
234 || vstop_event
->status
.kind
== TARGET_WAITKIND_VFORKED
)
235 && vstop_event
->status
.value
.related_pid
.matches (filter_ptid
))
244 in_queued_stop_replies (ptid_t ptid
)
246 for (notif_event
*event
: notif_stop
.queue
)
248 if (in_queued_stop_replies_ptid (event
, ptid
))
255 struct notif_server notif_stop
=
257 "vStopped", "Stop", {}, vstop_notif_reply
,
261 target_running (void)
263 return get_first_thread () != NULL
;
266 /* See gdbsupport/common-inferior.h. */
271 return !wrapper_argv
.empty () ? wrapper_argv
.c_str () : NULL
;
274 /* See gdbsupport/common-inferior.h. */
277 get_exec_file (int err
)
279 if (err
&& program_path
.get () == NULL
)
280 error (_("No executable file specified."));
282 return program_path
.get ();
294 attach_inferior (int pid
)
296 client_state
&cs
= get_client_state ();
297 /* myattach should return -1 if attaching is unsupported,
298 0 if it succeeded, and call error() otherwise. */
300 if (find_process_pid (pid
) != nullptr)
301 error ("Already attached to process %d\n", pid
);
303 if (myattach (pid
) != 0)
306 fprintf (stderr
, "Attached; pid = %d\n", pid
);
309 /* FIXME - It may be that we should get the SIGNAL_PID from the
310 attach function, so that it can be the main thread instead of
311 whichever we were told to attach to. */
316 cs
.last_ptid
= mywait (ptid_t (pid
), &cs
.last_status
, 0, 0);
318 /* GDB knows to ignore the first SIGSTOP after attaching to a running
319 process using the "attach" command, but this is different; it's
320 just using "target remote". Pretend it's just starting up. */
321 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
322 && cs
.last_status
.value
.sig
== GDB_SIGNAL_STOP
)
323 cs
.last_status
.value
.sig
= GDB_SIGNAL_TRAP
;
325 current_thread
->last_resume_kind
= resume_stop
;
326 current_thread
->last_status
= cs
.last_status
;
332 /* Decode a qXfer read request. Return 0 if everything looks OK,
336 decode_xfer_read (char *buf
, CORE_ADDR
*ofs
, unsigned int *len
)
338 /* After the read marker and annex, qXfer looks like a
339 traditional 'm' packet. */
340 decode_m_packet (buf
, ofs
, len
);
346 decode_xfer (char *buf
, char **object
, char **rw
, char **annex
, char **offset
)
348 /* Extract and NUL-terminate the object. */
350 while (*buf
&& *buf
!= ':')
356 /* Extract and NUL-terminate the read/write action. */
358 while (*buf
&& *buf
!= ':')
364 /* Extract and NUL-terminate the annex. */
366 while (*buf
&& *buf
!= ':')
376 /* Write the response to a successful qXfer read. Returns the
377 length of the (binary) data stored in BUF, corresponding
378 to as much of DATA/LEN as we could fit. IS_MORE controls
379 the first character of the response. */
381 write_qxfer_response (char *buf
, const gdb_byte
*data
, int len
, int is_more
)
390 return remote_escape_output (data
, len
, 1, (unsigned char *) buf
+ 1,
391 &out_len
, PBUFSIZ
- 2) + 1;
394 /* Handle btrace enabling in BTS format. */
397 handle_btrace_enable_bts (struct thread_info
*thread
)
399 if (thread
->btrace
!= NULL
)
400 error (_("Btrace already enabled."));
402 current_btrace_conf
.format
= BTRACE_FORMAT_BTS
;
403 thread
->btrace
= target_enable_btrace (thread
->id
, ¤t_btrace_conf
);
406 /* Handle btrace enabling in Intel Processor Trace format. */
409 handle_btrace_enable_pt (struct thread_info
*thread
)
411 if (thread
->btrace
!= NULL
)
412 error (_("Btrace already enabled."));
414 current_btrace_conf
.format
= BTRACE_FORMAT_PT
;
415 thread
->btrace
= target_enable_btrace (thread
->id
, ¤t_btrace_conf
);
418 /* Handle btrace disabling. */
421 handle_btrace_disable (struct thread_info
*thread
)
424 if (thread
->btrace
== NULL
)
425 error (_("Branch tracing not enabled."));
427 if (target_disable_btrace (thread
->btrace
) != 0)
428 error (_("Could not disable branch tracing."));
430 thread
->btrace
= NULL
;
433 /* Handle the "Qbtrace" packet. */
436 handle_btrace_general_set (char *own_buf
)
438 client_state
&cs
= get_client_state ();
439 struct thread_info
*thread
;
442 if (!startswith (own_buf
, "Qbtrace:"))
445 op
= own_buf
+ strlen ("Qbtrace:");
447 if (cs
.general_thread
== null_ptid
448 || cs
.general_thread
== minus_one_ptid
)
450 strcpy (own_buf
, "E.Must select a single thread.");
454 thread
= find_thread_ptid (cs
.general_thread
);
457 strcpy (own_buf
, "E.No such thread.");
463 if (strcmp (op
, "bts") == 0)
464 handle_btrace_enable_bts (thread
);
465 else if (strcmp (op
, "pt") == 0)
466 handle_btrace_enable_pt (thread
);
467 else if (strcmp (op
, "off") == 0)
468 handle_btrace_disable (thread
);
470 error (_("Bad Qbtrace operation. Use bts, pt, or off."));
474 catch (const gdb_exception_error
&exception
)
476 sprintf (own_buf
, "E.%s", exception
.what ());
482 /* Handle the "Qbtrace-conf" packet. */
485 handle_btrace_conf_general_set (char *own_buf
)
487 client_state
&cs
= get_client_state ();
488 struct thread_info
*thread
;
491 if (!startswith (own_buf
, "Qbtrace-conf:"))
494 op
= own_buf
+ strlen ("Qbtrace-conf:");
496 if (cs
.general_thread
== null_ptid
497 || cs
.general_thread
== minus_one_ptid
)
499 strcpy (own_buf
, "E.Must select a single thread.");
503 thread
= find_thread_ptid (cs
.general_thread
);
506 strcpy (own_buf
, "E.No such thread.");
510 if (startswith (op
, "bts:size="))
516 size
= strtoul (op
+ strlen ("bts:size="), &endp
, 16);
517 if (endp
== NULL
|| *endp
!= 0 || errno
!= 0 || size
> UINT_MAX
)
519 strcpy (own_buf
, "E.Bad size value.");
523 current_btrace_conf
.bts
.size
= (unsigned int) size
;
525 else if (strncmp (op
, "pt:size=", strlen ("pt:size=")) == 0)
531 size
= strtoul (op
+ strlen ("pt:size="), &endp
, 16);
532 if (endp
== NULL
|| *endp
!= 0 || errno
!= 0 || size
> UINT_MAX
)
534 strcpy (own_buf
, "E.Bad size value.");
538 current_btrace_conf
.pt
.size
= (unsigned int) size
;
542 strcpy (own_buf
, "E.Bad Qbtrace configuration option.");
550 /* Handle all of the extended 'Q' packets. */
553 handle_general_set (char *own_buf
)
555 client_state
&cs
= get_client_state ();
556 if (startswith (own_buf
, "QPassSignals:"))
558 int numsigs
= (int) GDB_SIGNAL_LAST
, i
;
559 const char *p
= own_buf
+ strlen ("QPassSignals:");
562 p
= decode_address_to_semicolon (&cursig
, p
);
563 for (i
= 0; i
< numsigs
; i
++)
567 cs
.pass_signals
[i
] = 1;
569 /* Keep looping, to clear the remaining signals. */
572 p
= decode_address_to_semicolon (&cursig
, p
);
575 cs
.pass_signals
[i
] = 0;
577 strcpy (own_buf
, "OK");
581 if (startswith (own_buf
, "QProgramSignals:"))
583 int numsigs
= (int) GDB_SIGNAL_LAST
, i
;
584 const char *p
= own_buf
+ strlen ("QProgramSignals:");
587 cs
.program_signals_p
= 1;
589 p
= decode_address_to_semicolon (&cursig
, p
);
590 for (i
= 0; i
< numsigs
; i
++)
594 cs
.program_signals
[i
] = 1;
596 /* Keep looping, to clear the remaining signals. */
599 p
= decode_address_to_semicolon (&cursig
, p
);
602 cs
.program_signals
[i
] = 0;
604 strcpy (own_buf
, "OK");
608 if (startswith (own_buf
, "QCatchSyscalls:"))
610 const char *p
= own_buf
+ sizeof ("QCatchSyscalls:") - 1;
613 struct process_info
*process
;
615 if (!target_running () || !target_supports_catch_syscall ())
621 if (strcmp (p
, "0") == 0)
623 else if (p
[0] == '1' && (p
[1] == ';' || p
[1] == '\0'))
627 fprintf (stderr
, "Unknown catch-syscalls mode requested: %s\n",
633 process
= current_process ();
634 process
->syscalls_to_catch
.clear ();
644 p
= decode_address_to_semicolon (&sysno
, p
);
645 process
->syscalls_to_catch
.push_back (sysno
);
649 process
->syscalls_to_catch
.push_back (ANY_SYSCALL
);
656 if (strcmp (own_buf
, "QEnvironmentReset") == 0)
658 our_environ
= gdb_environ::from_host_environ ();
664 if (startswith (own_buf
, "QEnvironmentHexEncoded:"))
666 const char *p
= own_buf
+ sizeof ("QEnvironmentHexEncoded:") - 1;
667 /* The final form of the environment variable. FINAL_VAR will
668 hold the 'VAR=VALUE' format. */
669 std::string final_var
= hex2str (p
);
670 std::string var_name
, var_value
;
674 debug_printf (_("[QEnvironmentHexEncoded received '%s']\n"), p
);
675 debug_printf (_("[Environment variable to be set: '%s']\n"),
680 size_t pos
= final_var
.find ('=');
681 if (pos
== std::string::npos
)
683 warning (_("Unexpected format for environment variable: '%s'"),
689 var_name
= final_var
.substr (0, pos
);
690 var_value
= final_var
.substr (pos
+ 1, std::string::npos
);
692 our_environ
.set (var_name
.c_str (), var_value
.c_str ());
698 if (startswith (own_buf
, "QEnvironmentUnset:"))
700 const char *p
= own_buf
+ sizeof ("QEnvironmentUnset:") - 1;
701 std::string varname
= hex2str (p
);
705 debug_printf (_("[QEnvironmentUnset received '%s']\n"), p
);
706 debug_printf (_("[Environment variable to be unset: '%s']\n"),
711 our_environ
.unset (varname
.c_str ());
717 if (strcmp (own_buf
, "QStartNoAckMode") == 0)
721 debug_printf ("[noack mode enabled]\n");
730 if (startswith (own_buf
, "QNonStop:"))
732 char *mode
= own_buf
+ 9;
736 if (strcmp (mode
, "0") == 0)
738 else if (strcmp (mode
, "1") == 0)
742 /* We don't know what this mode is, so complain to
744 fprintf (stderr
, "Unknown non-stop mode requested: %s\n",
750 req_str
= req
? "non-stop" : "all-stop";
751 if (the_target
->start_non_stop (req
== 1) != 0)
753 fprintf (stderr
, "Setting %s mode failed\n", req_str
);
758 non_stop
= (req
!= 0);
761 debug_printf ("[%s mode enabled]\n", req_str
);
767 if (startswith (own_buf
, "QDisableRandomization:"))
769 char *packet
= own_buf
+ strlen ("QDisableRandomization:");
772 unpack_varlen_hex (packet
, &setting
);
773 cs
.disable_randomization
= setting
;
777 debug_printf (cs
.disable_randomization
778 ? "[address space randomization disabled]\n"
779 : "[address space randomization enabled]\n");
786 if (target_supports_tracepoints ()
787 && handle_tracepoint_general_set (own_buf
))
790 if (startswith (own_buf
, "QAgent:"))
792 char *mode
= own_buf
+ strlen ("QAgent:");
795 if (strcmp (mode
, "0") == 0)
797 else if (strcmp (mode
, "1") == 0)
801 /* We don't know what this value is, so complain to GDB. */
802 sprintf (own_buf
, "E.Unknown QAgent value");
806 /* Update the flag. */
809 debug_printf ("[%s agent]\n", req
? "Enable" : "Disable");
814 if (handle_btrace_general_set (own_buf
))
817 if (handle_btrace_conf_general_set (own_buf
))
820 if (startswith (own_buf
, "QThreadEvents:"))
822 char *mode
= own_buf
+ strlen ("QThreadEvents:");
823 enum tribool req
= TRIBOOL_UNKNOWN
;
825 if (strcmp (mode
, "0") == 0)
827 else if (strcmp (mode
, "1") == 0)
831 /* We don't know what this mode is, so complain to GDB. */
833 = string_printf ("E.Unknown thread-events mode requested: %s\n",
835 strcpy (own_buf
, err
.c_str ());
839 cs
.report_thread_events
= (req
== TRIBOOL_TRUE
);
843 const char *req_str
= cs
.report_thread_events
? "enabled" : "disabled";
845 debug_printf ("[thread events are now %s]\n", req_str
);
852 if (startswith (own_buf
, "QStartupWithShell:"))
854 const char *value
= own_buf
+ strlen ("QStartupWithShell:");
856 if (strcmp (value
, "1") == 0)
857 startup_with_shell
= true;
858 else if (strcmp (value
, "0") == 0)
859 startup_with_shell
= false;
863 fprintf (stderr
, "Unknown value to startup-with-shell: %s\n",
870 debug_printf (_("[Inferior will %s started with shell]"),
871 startup_with_shell
? "be" : "not be");
877 if (startswith (own_buf
, "QSetWorkingDir:"))
879 const char *p
= own_buf
+ strlen ("QSetWorkingDir:");
883 std::string path
= hex2str (p
);
885 set_inferior_cwd (path
.c_str ());
888 debug_printf (_("[Set the inferior's current directory to %s]\n"),
893 /* An empty argument means that we should clear out any
894 previously set cwd for the inferior. */
895 set_inferior_cwd (NULL
);
899 [Unset the inferior's current directory; will use gdbserver's cwd]\n"));
906 /* Otherwise we didn't know what packet it was. Say we didn't
912 get_features_xml (const char *annex
)
914 const struct target_desc
*desc
= current_target_desc ();
916 /* `desc->xmltarget' defines what to return when looking for the
917 "target.xml" file. Its contents can either be verbatim XML code
918 (prefixed with a '@') or else the name of the actual XML file to
919 be used in place of "target.xml".
921 This variable is set up from the auto-generated
922 init_registers_... routine for the current target. */
924 if (strcmp (annex
, "target.xml") == 0)
926 const char *ret
= tdesc_get_features_xml (desc
);
938 /* Look for the annex. */
939 for (i
= 0; xml_builtin
[i
][0] != NULL
; i
++)
940 if (strcmp (annex
, xml_builtin
[i
][0]) == 0)
943 if (xml_builtin
[i
][0] != NULL
)
944 return xml_builtin
[i
][1];
952 monitor_show_help (void)
954 monitor_output ("The following monitor commands are supported:\n");
955 monitor_output (" set debug <0|1>\n");
956 monitor_output (" Enable general debugging messages\n");
957 monitor_output (" set debug-hw-points <0|1>\n");
958 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
959 monitor_output (" set remote-debug <0|1>\n");
960 monitor_output (" Enable remote protocol debugging messages\n");
961 monitor_output (" set event-loop-debug <0|1>\n");
962 monitor_output (" Enable event loop debugging messages\n");
963 monitor_output (" set debug-format option1[,option2,...]\n");
964 monitor_output (" Add additional information to debugging messages\n");
965 monitor_output (" Options: all, none");
966 monitor_output (", timestamp");
967 monitor_output ("\n");
968 monitor_output (" exit\n");
969 monitor_output (" Quit GDBserver\n");
972 /* Read trace frame or inferior memory. Returns the number of bytes
973 actually read, zero when no further transfer is possible, and -1 on
974 error. Return of a positive value smaller than LEN does not
975 indicate there's no more to be read, only the end of the transfer.
976 E.g., when GDB reads memory from a traceframe, a first request may
977 be served from a memory block that does not cover the whole request
978 length. A following request gets the rest served from either
979 another block (of the same traceframe) or from the read-only
983 gdb_read_memory (CORE_ADDR memaddr
, unsigned char *myaddr
, int len
)
985 client_state
&cs
= get_client_state ();
988 if (cs
.current_traceframe
>= 0)
991 ULONGEST length
= len
;
993 if (traceframe_read_mem (cs
.current_traceframe
,
994 memaddr
, myaddr
, len
, &nbytes
))
996 /* Data read from trace buffer, we're done. */
999 if (!in_readonly_region (memaddr
, length
))
1001 /* Otherwise we have a valid readonly case, fall through. */
1002 /* (assume no half-trace half-real blocks for now) */
1005 res
= prepare_to_access_memory ();
1008 if (set_desired_thread ())
1009 res
= read_inferior_memory (memaddr
, myaddr
, len
);
1012 done_accessing_memory ();
1014 return res
== 0 ? len
: -1;
1020 /* Write trace frame or inferior memory. Actually, writing to trace
1021 frames is forbidden. */
1024 gdb_write_memory (CORE_ADDR memaddr
, const unsigned char *myaddr
, int len
)
1026 client_state
&cs
= get_client_state ();
1027 if (cs
.current_traceframe
>= 0)
1033 ret
= prepare_to_access_memory ();
1036 if (set_desired_thread ())
1037 ret
= target_write_memory (memaddr
, myaddr
, len
);
1040 done_accessing_memory ();
1046 /* Handle qSearch:memory packets. */
1049 handle_search_memory (char *own_buf
, int packet_len
)
1051 CORE_ADDR start_addr
;
1052 CORE_ADDR search_space_len
;
1054 unsigned int pattern_len
;
1056 CORE_ADDR found_addr
;
1057 int cmd_name_len
= sizeof ("qSearch:memory:") - 1;
1059 pattern
= (gdb_byte
*) malloc (packet_len
);
1060 if (pattern
== NULL
)
1061 error ("Unable to allocate memory to perform the search");
1063 if (decode_search_memory_packet (own_buf
+ cmd_name_len
,
1064 packet_len
- cmd_name_len
,
1065 &start_addr
, &search_space_len
,
1066 pattern
, &pattern_len
) < 0)
1069 error ("Error in parsing qSearch:memory packet");
1072 auto read_memory
= [] (CORE_ADDR addr
, gdb_byte
*result
, size_t len
)
1074 return gdb_read_memory (addr
, result
, len
) == len
;
1077 found
= simple_search_memory (read_memory
, start_addr
, search_space_len
,
1078 pattern
, pattern_len
, &found_addr
);
1081 sprintf (own_buf
, "1,%lx", (long) found_addr
);
1082 else if (found
== 0)
1083 strcpy (own_buf
, "0");
1085 strcpy (own_buf
, "E00");
1090 /* Handle the "D" packet. */
1093 handle_detach (char *own_buf
)
1095 client_state
&cs
= get_client_state ();
1097 process_info
*process
;
1099 if (cs
.multi_process
)
1102 int pid
= strtol (&own_buf
[2], NULL
, 16);
1104 process
= find_process_pid (pid
);
1108 process
= (current_thread
!= nullptr
1109 ? get_thread_process (current_thread
)
1113 if (process
== NULL
)
1115 write_enn (own_buf
);
1119 if ((tracing
&& disconnected_tracing
) || any_persistent_commands (process
))
1121 if (tracing
&& disconnected_tracing
)
1123 "Disconnected tracing in effect, "
1124 "leaving gdbserver attached to the process\n");
1126 if (any_persistent_commands (process
))
1128 "Persistent commands are present, "
1129 "leaving gdbserver attached to the process\n");
1131 /* Make sure we're in non-stop/async mode, so we we can both
1132 wait for an async socket accept, and handle async target
1133 events simultaneously. There's also no point either in
1134 having the target stop all threads, when we're going to
1135 pass signals down without informing GDB. */
1139 debug_printf ("Forcing non-stop mode\n");
1142 the_target
->start_non_stop (true);
1145 process
->gdb_detached
= 1;
1147 /* Detaching implicitly resumes all threads. */
1148 target_continue_no_signal (minus_one_ptid
);
1154 fprintf (stderr
, "Detaching from process %d\n", process
->pid
);
1157 /* We'll need this after PROCESS has been destroyed. */
1158 int pid
= process
->pid
;
1160 if (detach_inferior (process
) != 0)
1161 write_enn (own_buf
);
1164 discard_queued_stop_replies (ptid_t (pid
));
1167 if (extended_protocol
|| target_running ())
1169 /* There is still at least one inferior remaining or
1170 we are in extended mode, so don't terminate gdbserver,
1171 and instead treat this like a normal program exit. */
1172 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
1173 cs
.last_status
.value
.integer
= 0;
1174 cs
.last_ptid
= ptid_t (pid
);
1176 current_thread
= NULL
;
1183 /* If we are attached, then we can exit. Otherwise, we
1184 need to hang around doing nothing, until the child is
1186 join_inferior (pid
);
1192 /* Parse options to --debug-format= and "monitor set debug-format".
1193 ARG is the text after "--debug-format=" or "monitor set debug-format".
1194 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1195 This triggers calls to monitor_output.
1196 The result is an empty string if all options were parsed ok, otherwise an
1197 error message which the caller must free.
1199 N.B. These commands affect all debug format settings, they are not
1200 cumulative. If a format is not specified, it is turned off.
1201 However, we don't go to extra trouble with things like
1202 "monitor set debug-format all,none,timestamp".
1203 Instead we just parse them one at a time, in order.
1205 The syntax for "monitor set debug" we support here is not identical
1206 to gdb's "set debug foo on|off" because we also use this function to
1207 parse "--debug-format=foo,bar". */
1210 parse_debug_format_options (const char *arg
, int is_monitor
)
1212 /* First turn all debug format options off. */
1213 debug_timestamp
= 0;
1215 /* First remove leading spaces, for "monitor set debug-format". */
1216 while (isspace (*arg
))
1219 std::vector
<gdb::unique_xmalloc_ptr
<char>> options
1220 = delim_string_to_char_ptr_vec (arg
, ',');
1222 for (const gdb::unique_xmalloc_ptr
<char> &option
: options
)
1224 if (strcmp (option
.get (), "all") == 0)
1226 debug_timestamp
= 1;
1228 monitor_output ("All extra debug format options enabled.\n");
1230 else if (strcmp (option
.get (), "none") == 0)
1232 debug_timestamp
= 0;
1234 monitor_output ("All extra debug format options disabled.\n");
1236 else if (strcmp (option
.get (), "timestamp") == 0)
1238 debug_timestamp
= 1;
1240 monitor_output ("Timestamps will be added to debug output.\n");
1242 else if (*option
== '\0')
1244 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1248 return string_printf ("Unknown debug-format argument: \"%s\"\n",
1252 return std::string ();
1255 /* Handle monitor commands not handled by target-specific handlers. */
1258 handle_monitor_command (char *mon
, char *own_buf
)
1260 if (strcmp (mon
, "set debug 1") == 0)
1263 monitor_output ("Debug output enabled.\n");
1265 else if (strcmp (mon
, "set debug 0") == 0)
1268 monitor_output ("Debug output disabled.\n");
1270 else if (strcmp (mon
, "set debug-hw-points 1") == 0)
1272 show_debug_regs
= 1;
1273 monitor_output ("H/W point debugging output enabled.\n");
1275 else if (strcmp (mon
, "set debug-hw-points 0") == 0)
1277 show_debug_regs
= 0;
1278 monitor_output ("H/W point debugging output disabled.\n");
1280 else if (strcmp (mon
, "set remote-debug 1") == 0)
1283 monitor_output ("Protocol debug output enabled.\n");
1285 else if (strcmp (mon
, "set remote-debug 0") == 0)
1288 monitor_output ("Protocol debug output disabled.\n");
1290 else if (strcmp (mon
, "set event-loop-debug 1") == 0)
1292 debug_event_loop
= debug_event_loop_kind::ALL
;
1293 monitor_output ("Event loop debug output enabled.\n");
1295 else if (strcmp (mon
, "set event-loop-debug 0") == 0)
1297 debug_event_loop
= debug_event_loop_kind::OFF
;
1298 monitor_output ("Event loop debug output disabled.\n");
1300 else if (startswith (mon
, "set debug-format "))
1302 std::string error_msg
1303 = parse_debug_format_options (mon
+ sizeof ("set debug-format ") - 1,
1306 if (!error_msg
.empty ())
1308 monitor_output (error_msg
.c_str ());
1309 monitor_show_help ();
1310 write_enn (own_buf
);
1313 else if (strcmp (mon
, "set debug-file") == 0)
1314 debug_set_output (nullptr);
1315 else if (startswith (mon
, "set debug-file "))
1316 debug_set_output (mon
+ sizeof ("set debug-file ") - 1);
1317 else if (strcmp (mon
, "help") == 0)
1318 monitor_show_help ();
1319 else if (strcmp (mon
, "exit") == 0)
1320 exit_requested
= true;
1323 monitor_output ("Unknown monitor command.\n\n");
1324 monitor_show_help ();
1325 write_enn (own_buf
);
1329 /* Associates a callback with each supported qXfer'able object. */
1333 /* The object this handler handles. */
1336 /* Request that the target transfer up to LEN 8-bit bytes of the
1337 target's OBJECT. The OFFSET, for a seekable object, specifies
1338 the starting point. The ANNEX can be used to provide additional
1339 data-specific information to the target.
1341 Return the number of bytes actually transfered, zero when no
1342 further transfer is possible, -1 on error, -2 when the transfer
1343 is not supported, and -3 on a verbose error message that should
1344 be preserved. Return of a positive value smaller than LEN does
1345 not indicate the end of the object, only the end of the transfer.
1347 One, and only one, of readbuf or writebuf must be non-NULL. */
1348 int (*xfer
) (const char *annex
,
1349 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1350 ULONGEST offset
, LONGEST len
);
1353 /* Handle qXfer:auxv:read. */
1356 handle_qxfer_auxv (const char *annex
,
1357 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1358 ULONGEST offset
, LONGEST len
)
1360 if (!the_target
->supports_read_auxv () || writebuf
!= NULL
)
1363 if (annex
[0] != '\0' || current_thread
== NULL
)
1366 return the_target
->read_auxv (offset
, readbuf
, len
);
1369 /* Handle qXfer:exec-file:read. */
1372 handle_qxfer_exec_file (const char *annex
,
1373 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1374 ULONGEST offset
, LONGEST len
)
1380 if (!the_target
->supports_pid_to_exec_file () || writebuf
!= NULL
)
1383 if (annex
[0] == '\0')
1385 if (current_thread
== NULL
)
1388 pid
= pid_of (current_thread
);
1392 annex
= unpack_varlen_hex (annex
, &pid
);
1393 if (annex
[0] != '\0')
1400 file
= the_target
->pid_to_exec_file (pid
);
1404 total_len
= strlen (file
);
1406 if (offset
> total_len
)
1409 if (offset
+ len
> total_len
)
1410 len
= total_len
- offset
;
1412 memcpy (readbuf
, file
+ offset
, len
);
1416 /* Handle qXfer:features:read. */
1419 handle_qxfer_features (const char *annex
,
1420 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1421 ULONGEST offset
, LONGEST len
)
1423 const char *document
;
1426 if (writebuf
!= NULL
)
1429 if (!target_running ())
1432 /* Grab the correct annex. */
1433 document
= get_features_xml (annex
);
1434 if (document
== NULL
)
1437 total_len
= strlen (document
);
1439 if (offset
> total_len
)
1442 if (offset
+ len
> total_len
)
1443 len
= total_len
- offset
;
1445 memcpy (readbuf
, document
+ offset
, len
);
1449 /* Handle qXfer:libraries:read. */
1452 handle_qxfer_libraries (const char *annex
,
1453 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1454 ULONGEST offset
, LONGEST len
)
1456 if (writebuf
!= NULL
)
1459 if (annex
[0] != '\0' || current_thread
== NULL
)
1462 std::string document
= "<library-list version=\"1.0\">\n";
1464 for (const dll_info
&dll
: all_dlls
)
1465 document
+= string_printf
1466 (" <library name=\"%s\"><segment address=\"0x%s\"/></library>\n",
1467 dll
.name
.c_str (), paddress (dll
.base_addr
));
1469 document
+= "</library-list>\n";
1471 if (offset
> document
.length ())
1474 if (offset
+ len
> document
.length ())
1475 len
= document
.length () - offset
;
1477 memcpy (readbuf
, &document
[offset
], len
);
1482 /* Handle qXfer:libraries-svr4:read. */
1485 handle_qxfer_libraries_svr4 (const char *annex
,
1486 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1487 ULONGEST offset
, LONGEST len
)
1489 if (writebuf
!= NULL
)
1492 if (current_thread
== NULL
1493 || !the_target
->supports_qxfer_libraries_svr4 ())
1496 return the_target
->qxfer_libraries_svr4 (annex
, readbuf
, writebuf
,
1500 /* Handle qXfer:osadata:read. */
1503 handle_qxfer_osdata (const char *annex
,
1504 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1505 ULONGEST offset
, LONGEST len
)
1507 if (!the_target
->supports_qxfer_osdata () || writebuf
!= NULL
)
1510 return the_target
->qxfer_osdata (annex
, readbuf
, NULL
, offset
, len
);
1513 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1516 handle_qxfer_siginfo (const char *annex
,
1517 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1518 ULONGEST offset
, LONGEST len
)
1520 if (!the_target
->supports_qxfer_siginfo ())
1523 if (annex
[0] != '\0' || current_thread
== NULL
)
1526 return the_target
->qxfer_siginfo (annex
, readbuf
, writebuf
, offset
, len
);
1529 /* Handle qXfer:statictrace:read. */
1532 handle_qxfer_statictrace (const char *annex
,
1533 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1534 ULONGEST offset
, LONGEST len
)
1536 client_state
&cs
= get_client_state ();
1539 if (writebuf
!= NULL
)
1542 if (annex
[0] != '\0' || current_thread
== NULL
1543 || cs
.current_traceframe
== -1)
1546 if (traceframe_read_sdata (cs
.current_traceframe
, offset
,
1547 readbuf
, len
, &nbytes
))
1552 /* Helper for handle_qxfer_threads_proper.
1553 Emit the XML to describe the thread of INF. */
1556 handle_qxfer_threads_worker (thread_info
*thread
, struct buffer
*buffer
)
1558 ptid_t ptid
= ptid_of (thread
);
1560 int core
= target_core_of_thread (ptid
);
1562 const char *name
= target_thread_name (ptid
);
1565 bool handle_status
= target_thread_handle (ptid
, &handle
, &handle_len
);
1567 write_ptid (ptid_s
, ptid
);
1569 buffer_xml_printf (buffer
, "<thread id=\"%s\"", ptid_s
);
1573 sprintf (core_s
, "%d", core
);
1574 buffer_xml_printf (buffer
, " core=\"%s\"", core_s
);
1578 buffer_xml_printf (buffer
, " name=\"%s\"", name
);
1582 char *handle_s
= (char *) alloca (handle_len
* 2 + 1);
1583 bin2hex (handle
, handle_s
, handle_len
);
1584 buffer_xml_printf (buffer
, " handle=\"%s\"", handle_s
);
1587 buffer_xml_printf (buffer
, "/>\n");
1590 /* Helper for handle_qxfer_threads. Return true on success, false
1594 handle_qxfer_threads_proper (struct buffer
*buffer
)
1596 client_state
&cs
= get_client_state ();
1598 scoped_restore save_current_thread
1599 = make_scoped_restore (¤t_thread
);
1600 scoped_restore save_current_general_thread
1601 = make_scoped_restore (&cs
.general_thread
);
1603 buffer_grow_str (buffer
, "<threads>\n");
1605 process_info
*error_proc
= find_process ([&] (process_info
*process
)
1607 /* The target may need to access memory and registers (e.g. via
1608 libthread_db) to fetch thread properties. Prepare for memory
1609 access here, so that we potentially pause threads just once
1610 for all accesses. Note that even if someday we stop needing
1611 to pause threads to access memory, we will need to be able to
1612 access registers, or other ptrace accesses like
1613 PTRACE_GET_THREAD_AREA. */
1615 /* Need to switch to each process in turn, because
1616 prepare_to_access_memory prepares for an access in the
1617 current process pointed to by general_thread. */
1618 switch_to_process (process
);
1619 cs
.general_thread
= current_thread
->id
;
1621 int res
= prepare_to_access_memory ();
1624 for_each_thread (process
->pid
, [&] (thread_info
*thread
)
1626 handle_qxfer_threads_worker (thread
, buffer
);
1629 done_accessing_memory ();
1636 buffer_grow_str0 (buffer
, "</threads>\n");
1637 return error_proc
== nullptr;
1640 /* Handle qXfer:threads:read. */
1643 handle_qxfer_threads (const char *annex
,
1644 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1645 ULONGEST offset
, LONGEST len
)
1647 static char *result
= 0;
1648 static unsigned int result_length
= 0;
1650 if (writebuf
!= NULL
)
1653 if (annex
[0] != '\0')
1658 struct buffer buffer
;
1659 /* When asked for data at offset 0, generate everything and store into
1660 'result'. Successive reads will be served off 'result'. */
1664 buffer_init (&buffer
);
1666 bool res
= handle_qxfer_threads_proper (&buffer
);
1668 result
= buffer_finish (&buffer
);
1669 result_length
= strlen (result
);
1670 buffer_free (&buffer
);
1676 if (offset
>= result_length
)
1678 /* We're out of data. */
1685 if (len
> result_length
- offset
)
1686 len
= result_length
- offset
;
1688 memcpy (readbuf
, result
+ offset
, len
);
1693 /* Handle qXfer:traceframe-info:read. */
1696 handle_qxfer_traceframe_info (const char *annex
,
1697 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1698 ULONGEST offset
, LONGEST len
)
1700 client_state
&cs
= get_client_state ();
1701 static char *result
= 0;
1702 static unsigned int result_length
= 0;
1704 if (writebuf
!= NULL
)
1707 if (!target_running () || annex
[0] != '\0' || cs
.current_traceframe
== -1)
1712 struct buffer buffer
;
1714 /* When asked for data at offset 0, generate everything and
1715 store into 'result'. Successive reads will be served off
1719 buffer_init (&buffer
);
1721 traceframe_read_info (cs
.current_traceframe
, &buffer
);
1723 result
= buffer_finish (&buffer
);
1724 result_length
= strlen (result
);
1725 buffer_free (&buffer
);
1728 if (offset
>= result_length
)
1730 /* We're out of data. */
1737 if (len
> result_length
- offset
)
1738 len
= result_length
- offset
;
1740 memcpy (readbuf
, result
+ offset
, len
);
1744 /* Handle qXfer:fdpic:read. */
1747 handle_qxfer_fdpic (const char *annex
, gdb_byte
*readbuf
,
1748 const gdb_byte
*writebuf
, ULONGEST offset
, LONGEST len
)
1750 if (!the_target
->supports_read_loadmap ())
1753 if (current_thread
== NULL
)
1756 return the_target
->read_loadmap (annex
, offset
, readbuf
, len
);
1759 /* Handle qXfer:btrace:read. */
1762 handle_qxfer_btrace (const char *annex
,
1763 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1764 ULONGEST offset
, LONGEST len
)
1766 client_state
&cs
= get_client_state ();
1767 static struct buffer cache
;
1768 struct thread_info
*thread
;
1769 enum btrace_read_type type
;
1772 if (writebuf
!= NULL
)
1775 if (cs
.general_thread
== null_ptid
1776 || cs
.general_thread
== minus_one_ptid
)
1778 strcpy (cs
.own_buf
, "E.Must select a single thread.");
1782 thread
= find_thread_ptid (cs
.general_thread
);
1785 strcpy (cs
.own_buf
, "E.No such thread.");
1789 if (thread
->btrace
== NULL
)
1791 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
1795 if (strcmp (annex
, "all") == 0)
1796 type
= BTRACE_READ_ALL
;
1797 else if (strcmp (annex
, "new") == 0)
1798 type
= BTRACE_READ_NEW
;
1799 else if (strcmp (annex
, "delta") == 0)
1800 type
= BTRACE_READ_DELTA
;
1803 strcpy (cs
.own_buf
, "E.Bad annex.");
1809 buffer_free (&cache
);
1813 result
= target_read_btrace (thread
->btrace
, &cache
, type
);
1815 memcpy (cs
.own_buf
, cache
.buffer
, cache
.used_size
);
1817 catch (const gdb_exception_error
&exception
)
1819 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
1826 else if (offset
> cache
.used_size
)
1828 buffer_free (&cache
);
1832 if (len
> cache
.used_size
- offset
)
1833 len
= cache
.used_size
- offset
;
1835 memcpy (readbuf
, cache
.buffer
+ offset
, len
);
1840 /* Handle qXfer:btrace-conf:read. */
1843 handle_qxfer_btrace_conf (const char *annex
,
1844 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1845 ULONGEST offset
, LONGEST len
)
1847 client_state
&cs
= get_client_state ();
1848 static struct buffer cache
;
1849 struct thread_info
*thread
;
1852 if (writebuf
!= NULL
)
1855 if (annex
[0] != '\0')
1858 if (cs
.general_thread
== null_ptid
1859 || cs
.general_thread
== minus_one_ptid
)
1861 strcpy (cs
.own_buf
, "E.Must select a single thread.");
1865 thread
= find_thread_ptid (cs
.general_thread
);
1868 strcpy (cs
.own_buf
, "E.No such thread.");
1872 if (thread
->btrace
== NULL
)
1874 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
1880 buffer_free (&cache
);
1884 result
= target_read_btrace_conf (thread
->btrace
, &cache
);
1886 memcpy (cs
.own_buf
, cache
.buffer
, cache
.used_size
);
1888 catch (const gdb_exception_error
&exception
)
1890 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
1897 else if (offset
> cache
.used_size
)
1899 buffer_free (&cache
);
1903 if (len
> cache
.used_size
- offset
)
1904 len
= cache
.used_size
- offset
;
1906 memcpy (readbuf
, cache
.buffer
+ offset
, len
);
1911 static const struct qxfer qxfer_packets
[] =
1913 { "auxv", handle_qxfer_auxv
},
1914 { "btrace", handle_qxfer_btrace
},
1915 { "btrace-conf", handle_qxfer_btrace_conf
},
1916 { "exec-file", handle_qxfer_exec_file
},
1917 { "fdpic", handle_qxfer_fdpic
},
1918 { "features", handle_qxfer_features
},
1919 { "libraries", handle_qxfer_libraries
},
1920 { "libraries-svr4", handle_qxfer_libraries_svr4
},
1921 { "osdata", handle_qxfer_osdata
},
1922 { "siginfo", handle_qxfer_siginfo
},
1923 { "statictrace", handle_qxfer_statictrace
},
1924 { "threads", handle_qxfer_threads
},
1925 { "traceframe-info", handle_qxfer_traceframe_info
},
1929 handle_qxfer (char *own_buf
, int packet_len
, int *new_packet_len_p
)
1937 if (!startswith (own_buf
, "qXfer:"))
1940 /* Grab the object, r/w and annex. */
1941 if (decode_xfer (own_buf
+ 6, &object
, &rw
, &annex
, &offset
) < 0)
1943 write_enn (own_buf
);
1948 i
< sizeof (qxfer_packets
) / sizeof (qxfer_packets
[0]);
1951 const struct qxfer
*q
= &qxfer_packets
[i
];
1953 if (strcmp (object
, q
->object
) == 0)
1955 if (strcmp (rw
, "read") == 0)
1957 unsigned char *data
;
1962 /* Grab the offset and length. */
1963 if (decode_xfer_read (offset
, &ofs
, &len
) < 0)
1965 write_enn (own_buf
);
1969 /* Read one extra byte, as an indicator of whether there is
1971 if (len
> PBUFSIZ
- 2)
1973 data
= (unsigned char *) malloc (len
+ 1);
1976 write_enn (own_buf
);
1979 n
= (*q
->xfer
) (annex
, data
, NULL
, ofs
, len
+ 1);
1987 /* Preserve error message. */
1990 write_enn (own_buf
);
1992 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, len
, 1);
1994 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, n
, 0);
1999 else if (strcmp (rw
, "write") == 0)
2004 unsigned char *data
;
2006 strcpy (own_buf
, "E00");
2007 data
= (unsigned char *) malloc (packet_len
- (offset
- own_buf
));
2010 write_enn (own_buf
);
2013 if (decode_xfer_write (offset
, packet_len
- (offset
- own_buf
),
2014 &ofs
, &len
, data
) < 0)
2017 write_enn (own_buf
);
2021 n
= (*q
->xfer
) (annex
, NULL
, data
, ofs
, len
);
2029 /* Preserve error message. */
2032 write_enn (own_buf
);
2034 sprintf (own_buf
, "%x", n
);
2047 /* Compute 32 bit CRC from inferior memory.
2049 On success, return 32 bit CRC.
2050 On failure, return (unsigned long long) -1. */
2052 static unsigned long long
2053 crc32 (CORE_ADDR base
, int len
, unsigned int crc
)
2057 unsigned char byte
= 0;
2059 /* Return failure if memory read fails. */
2060 if (read_inferior_memory (base
, &byte
, 1) != 0)
2061 return (unsigned long long) -1;
2063 crc
= xcrc32 (&byte
, 1, crc
);
2066 return (unsigned long long) crc
;
2069 /* Add supported btrace packets to BUF. */
2072 supported_btrace_packets (char *buf
)
2074 strcat (buf
, ";Qbtrace:bts+");
2075 strcat (buf
, ";Qbtrace-conf:bts:size+");
2076 strcat (buf
, ";Qbtrace:pt+");
2077 strcat (buf
, ";Qbtrace-conf:pt:size+");
2078 strcat (buf
, ";Qbtrace:off+");
2079 strcat (buf
, ";qXfer:btrace:read+");
2080 strcat (buf
, ";qXfer:btrace-conf:read+");
2083 /* Handle all of the extended 'q' packets. */
2086 handle_query (char *own_buf
, int packet_len
, int *new_packet_len_p
)
2088 client_state
&cs
= get_client_state ();
2089 static std::list
<thread_info
*>::const_iterator thread_iter
;
2091 /* Reply the current thread id. */
2092 if (strcmp ("qC", own_buf
) == 0 && !disable_packet_qC
)
2095 require_running_or_return (own_buf
);
2097 if (cs
.general_thread
!= null_ptid
&& cs
.general_thread
!= minus_one_ptid
)
2098 ptid
= cs
.general_thread
;
2101 thread_iter
= all_threads
.begin ();
2102 ptid
= (*thread_iter
)->id
;
2105 sprintf (own_buf
, "QC");
2107 write_ptid (own_buf
, ptid
);
2111 if (strcmp ("qSymbol::", own_buf
) == 0)
2113 struct thread_info
*save_thread
= current_thread
;
2115 /* For qSymbol, GDB only changes the current thread if the
2116 previous current thread was of a different process. So if
2117 the previous thread is gone, we need to pick another one of
2118 the same process. This can happen e.g., if we followed an
2119 exec in a non-leader thread. */
2120 if (current_thread
== NULL
)
2123 = find_any_thread_of_pid (cs
.general_thread
.pid ());
2125 /* Just in case, if we didn't find a thread, then bail out
2126 instead of crashing. */
2127 if (current_thread
== NULL
)
2129 write_enn (own_buf
);
2130 current_thread
= save_thread
;
2135 /* GDB is suggesting new symbols have been loaded. This may
2136 mean a new shared library has been detected as loaded, so
2137 take the opportunity to check if breakpoints we think are
2138 inserted, still are. Note that it isn't guaranteed that
2139 we'll see this when a shared library is loaded, and nor will
2140 we see this for unloads (although breakpoints in unloaded
2141 libraries shouldn't trigger), as GDB may not find symbols for
2142 the library at all. We also re-validate breakpoints when we
2143 see a second GDB breakpoint for the same address, and or when
2144 we access breakpoint shadows. */
2145 validate_breakpoints ();
2147 if (target_supports_tracepoints ())
2148 tracepoint_look_up_symbols ();
2150 if (current_thread
!= NULL
)
2151 the_target
->look_up_symbols ();
2153 current_thread
= save_thread
;
2155 strcpy (own_buf
, "OK");
2159 if (!disable_packet_qfThreadInfo
)
2161 if (strcmp ("qfThreadInfo", own_buf
) == 0)
2163 require_running_or_return (own_buf
);
2164 thread_iter
= all_threads
.begin ();
2167 ptid_t ptid
= (*thread_iter
)->id
;
2168 write_ptid (own_buf
, ptid
);
2173 if (strcmp ("qsThreadInfo", own_buf
) == 0)
2175 require_running_or_return (own_buf
);
2176 if (thread_iter
!= all_threads
.end ())
2179 ptid_t ptid
= (*thread_iter
)->id
;
2180 write_ptid (own_buf
, ptid
);
2186 sprintf (own_buf
, "l");
2192 if (the_target
->supports_read_offsets ()
2193 && strcmp ("qOffsets", own_buf
) == 0)
2195 CORE_ADDR text
, data
;
2197 require_running_or_return (own_buf
);
2198 if (the_target
->read_offsets (&text
, &data
))
2199 sprintf (own_buf
, "Text=%lX;Data=%lX;Bss=%lX",
2200 (long)text
, (long)data
, (long)data
);
2202 write_enn (own_buf
);
2207 /* Protocol features query. */
2208 if (startswith (own_buf
, "qSupported")
2209 && (own_buf
[10] == ':' || own_buf
[10] == '\0'))
2211 char *p
= &own_buf
[10];
2212 int gdb_supports_qRelocInsn
= 0;
2214 /* Process each feature being provided by GDB. The first
2215 feature will follow a ':', and latter features will follow
2219 std::vector
<std::string
> qsupported
;
2220 std::vector
<const char *> unknowns
;
2222 /* Two passes, to avoid nested strtok calls in
2223 target_process_qsupported. */
2225 for (p
= strtok_r (p
+ 1, ";", &saveptr
);
2227 p
= strtok_r (NULL
, ";", &saveptr
))
2228 qsupported
.emplace_back (p
);
2230 for (const std::string
&feature
: qsupported
)
2232 if (feature
== "multiprocess+")
2234 /* GDB supports and wants multi-process support if
2236 if (target_supports_multi_process ())
2237 cs
.multi_process
= 1;
2239 else if (feature
== "qRelocInsn+")
2241 /* GDB supports relocate instruction requests. */
2242 gdb_supports_qRelocInsn
= 1;
2244 else if (feature
== "swbreak+")
2246 /* GDB wants us to report whether a trap is caused
2247 by a software breakpoint and for us to handle PC
2248 adjustment if necessary on this target. */
2249 if (target_supports_stopped_by_sw_breakpoint ())
2250 cs
.swbreak_feature
= 1;
2252 else if (feature
== "hwbreak+")
2254 /* GDB wants us to report whether a trap is caused
2255 by a hardware breakpoint. */
2256 if (target_supports_stopped_by_hw_breakpoint ())
2257 cs
.hwbreak_feature
= 1;
2259 else if (feature
== "fork-events+")
2261 /* GDB supports and wants fork events if possible. */
2262 if (target_supports_fork_events ())
2263 cs
.report_fork_events
= 1;
2265 else if (feature
== "vfork-events+")
2267 /* GDB supports and wants vfork events if possible. */
2268 if (target_supports_vfork_events ())
2269 cs
.report_vfork_events
= 1;
2271 else if (feature
== "exec-events+")
2273 /* GDB supports and wants exec events if possible. */
2274 if (target_supports_exec_events ())
2275 cs
.report_exec_events
= 1;
2277 else if (feature
== "vContSupported+")
2278 cs
.vCont_supported
= 1;
2279 else if (feature
== "QThreadEvents+")
2281 else if (feature
== "no-resumed+")
2283 /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
2285 report_no_resumed
= true;
2289 /* Move the unknown features all together. */
2290 unknowns
.push_back (feature
.c_str ());
2294 /* Give the target backend a chance to process the unknown
2296 target_process_qsupported (unknowns
);
2300 "PacketSize=%x;QPassSignals+;QProgramSignals+;"
2301 "QStartupWithShell+;QEnvironmentHexEncoded+;"
2302 "QEnvironmentReset+;QEnvironmentUnset+;"
2306 if (target_supports_catch_syscall ())
2307 strcat (own_buf
, ";QCatchSyscalls+");
2309 if (the_target
->supports_qxfer_libraries_svr4 ())
2310 strcat (own_buf
, ";qXfer:libraries-svr4:read+"
2311 ";augmented-libraries-svr4-read+");
2314 /* We do not have any hook to indicate whether the non-SVR4 target
2315 backend supports qXfer:libraries:read, so always report it. */
2316 strcat (own_buf
, ";qXfer:libraries:read+");
2319 if (the_target
->supports_read_auxv ())
2320 strcat (own_buf
, ";qXfer:auxv:read+");
2322 if (the_target
->supports_qxfer_siginfo ())
2323 strcat (own_buf
, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2325 if (the_target
->supports_read_loadmap ())
2326 strcat (own_buf
, ";qXfer:fdpic:read+");
2328 /* We always report qXfer:features:read, as targets may
2329 install XML files on a subsequent call to arch_setup.
2330 If we reported to GDB on startup that we don't support
2331 qXfer:feature:read at all, we will never be re-queried. */
2332 strcat (own_buf
, ";qXfer:features:read+");
2334 if (cs
.transport_is_reliable
)
2335 strcat (own_buf
, ";QStartNoAckMode+");
2337 if (the_target
->supports_qxfer_osdata ())
2338 strcat (own_buf
, ";qXfer:osdata:read+");
2340 if (target_supports_multi_process ())
2341 strcat (own_buf
, ";multiprocess+");
2343 if (target_supports_fork_events ())
2344 strcat (own_buf
, ";fork-events+");
2346 if (target_supports_vfork_events ())
2347 strcat (own_buf
, ";vfork-events+");
2349 if (target_supports_exec_events ())
2350 strcat (own_buf
, ";exec-events+");
2352 if (target_supports_non_stop ())
2353 strcat (own_buf
, ";QNonStop+");
2355 if (target_supports_disable_randomization ())
2356 strcat (own_buf
, ";QDisableRandomization+");
2358 strcat (own_buf
, ";qXfer:threads:read+");
2360 if (target_supports_tracepoints ())
2362 strcat (own_buf
, ";ConditionalTracepoints+");
2363 strcat (own_buf
, ";TraceStateVariables+");
2364 strcat (own_buf
, ";TracepointSource+");
2365 strcat (own_buf
, ";DisconnectedTracing+");
2366 if (gdb_supports_qRelocInsn
&& target_supports_fast_tracepoints ())
2367 strcat (own_buf
, ";FastTracepoints+");
2368 strcat (own_buf
, ";StaticTracepoints+");
2369 strcat (own_buf
, ";InstallInTrace+");
2370 strcat (own_buf
, ";qXfer:statictrace:read+");
2371 strcat (own_buf
, ";qXfer:traceframe-info:read+");
2372 strcat (own_buf
, ";EnableDisableTracepoints+");
2373 strcat (own_buf
, ";QTBuffer:size+");
2374 strcat (own_buf
, ";tracenz+");
2377 if (target_supports_hardware_single_step ()
2378 || target_supports_software_single_step () )
2380 strcat (own_buf
, ";ConditionalBreakpoints+");
2382 strcat (own_buf
, ";BreakpointCommands+");
2384 if (target_supports_agent ())
2385 strcat (own_buf
, ";QAgent+");
2387 supported_btrace_packets (own_buf
);
2389 if (target_supports_stopped_by_sw_breakpoint ())
2390 strcat (own_buf
, ";swbreak+");
2392 if (target_supports_stopped_by_hw_breakpoint ())
2393 strcat (own_buf
, ";hwbreak+");
2395 if (the_target
->supports_pid_to_exec_file ())
2396 strcat (own_buf
, ";qXfer:exec-file:read+");
2398 strcat (own_buf
, ";vContSupported+");
2400 strcat (own_buf
, ";QThreadEvents+");
2402 strcat (own_buf
, ";no-resumed+");
2404 /* Reinitialize components as needed for the new connection. */
2405 hostio_handle_new_gdb_connection ();
2406 target_handle_new_gdb_connection ();
2411 /* Thread-local storage support. */
2412 if (the_target
->supports_get_tls_address ()
2413 && startswith (own_buf
, "qGetTLSAddr:"))
2415 char *p
= own_buf
+ 12;
2416 CORE_ADDR parts
[2], address
= 0;
2418 ptid_t ptid
= null_ptid
;
2420 require_running_or_return (own_buf
);
2422 for (i
= 0; i
< 3; i
++)
2430 p2
= strchr (p
, ',');
2443 ptid
= read_ptid (p
, NULL
);
2445 decode_address (&parts
[i
- 1], p
, len
);
2449 if (p
!= NULL
|| i
< 3)
2453 struct thread_info
*thread
= find_thread_ptid (ptid
);
2458 err
= the_target
->get_tls_address (thread
, parts
[0], parts
[1],
2464 strcpy (own_buf
, paddress(address
));
2469 write_enn (own_buf
);
2473 /* Otherwise, pretend we do not understand this packet. */
2476 /* Windows OS Thread Information Block address support. */
2477 if (the_target
->supports_get_tib_address ()
2478 && startswith (own_buf
, "qGetTIBAddr:"))
2483 ptid_t ptid
= read_ptid (own_buf
+ 12, &annex
);
2485 n
= the_target
->get_tib_address (ptid
, &tlb
);
2488 strcpy (own_buf
, paddress(tlb
));
2493 write_enn (own_buf
);
2499 /* Handle "monitor" commands. */
2500 if (startswith (own_buf
, "qRcmd,"))
2502 char *mon
= (char *) malloc (PBUFSIZ
);
2503 int len
= strlen (own_buf
+ 6);
2507 write_enn (own_buf
);
2512 || hex2bin (own_buf
+ 6, (gdb_byte
*) mon
, len
/ 2) != len
/ 2)
2514 write_enn (own_buf
);
2518 mon
[len
/ 2] = '\0';
2522 if (the_target
->handle_monitor_command (mon
) == 0)
2523 /* Default processing. */
2524 handle_monitor_command (mon
, own_buf
);
2530 if (startswith (own_buf
, "qSearch:memory:"))
2532 require_running_or_return (own_buf
);
2533 handle_search_memory (own_buf
, packet_len
);
2537 if (strcmp (own_buf
, "qAttached") == 0
2538 || startswith (own_buf
, "qAttached:"))
2540 struct process_info
*process
;
2542 if (own_buf
[sizeof ("qAttached") - 1])
2544 int pid
= strtoul (own_buf
+ sizeof ("qAttached:") - 1, NULL
, 16);
2545 process
= find_process_pid (pid
);
2549 require_running_or_return (own_buf
);
2550 process
= current_process ();
2553 if (process
== NULL
)
2555 write_enn (own_buf
);
2559 strcpy (own_buf
, process
->attached
? "1" : "0");
2563 if (startswith (own_buf
, "qCRC:"))
2565 /* CRC check (compare-section). */
2569 unsigned long long crc
;
2571 require_running_or_return (own_buf
);
2572 comma
= unpack_varlen_hex (own_buf
+ 5, &base
);
2573 if (*comma
++ != ',')
2575 write_enn (own_buf
);
2578 len
= strtoul (comma
, NULL
, 16);
2579 crc
= crc32 (base
, len
, 0xffffffff);
2580 /* Check for memory failure. */
2581 if (crc
== (unsigned long long) -1)
2583 write_enn (own_buf
);
2586 sprintf (own_buf
, "C%lx", (unsigned long) crc
);
2590 if (handle_qxfer (own_buf
, packet_len
, new_packet_len_p
))
2593 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf
))
2596 /* Otherwise we didn't know what packet it was. Say we didn't
2601 static void gdb_wants_all_threads_stopped (void);
2602 static void resume (struct thread_resume
*actions
, size_t n
);
2604 /* The callback that is passed to visit_actioned_threads. */
2605 typedef int (visit_actioned_threads_callback_ftype
)
2606 (const struct thread_resume
*, struct thread_info
*);
2608 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
2609 true if CALLBACK returns true. Returns false if no matching thread
2610 is found or CALLBACK results false.
2611 Note: This function is itself a callback for find_thread. */
2614 visit_actioned_threads (thread_info
*thread
,
2615 const struct thread_resume
*actions
,
2617 visit_actioned_threads_callback_ftype
*callback
)
2619 for (size_t i
= 0; i
< num_actions
; i
++)
2621 const struct thread_resume
*action
= &actions
[i
];
2623 if (action
->thread
== minus_one_ptid
2624 || action
->thread
== thread
->id
2625 || ((action
->thread
.pid ()
2626 == thread
->id
.pid ())
2627 && action
->thread
.lwp () == -1))
2629 if ((*callback
) (action
, thread
))
2637 /* Callback for visit_actioned_threads. If the thread has a pending
2638 status to report, report it now. */
2641 handle_pending_status (const struct thread_resume
*resumption
,
2642 struct thread_info
*thread
)
2644 client_state
&cs
= get_client_state ();
2645 if (thread
->status_pending_p
)
2647 thread
->status_pending_p
= 0;
2649 cs
.last_status
= thread
->last_status
;
2650 cs
.last_ptid
= thread
->id
;
2651 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, &cs
.last_status
);
2657 /* Parse vCont packets. */
2659 handle_v_cont (char *own_buf
)
2663 struct thread_resume
*resume_info
;
2664 struct thread_resume default_action
{ null_ptid
};
2666 /* Count the number of semicolons in the packet. There should be one
2667 for every action. */
2673 p
= strchr (p
, ';');
2676 resume_info
= (struct thread_resume
*) malloc (n
* sizeof (resume_info
[0]));
2677 if (resume_info
== NULL
)
2685 memset (&resume_info
[i
], 0, sizeof resume_info
[i
]);
2687 if (p
[0] == 's' || p
[0] == 'S')
2688 resume_info
[i
].kind
= resume_step
;
2689 else if (p
[0] == 'r')
2690 resume_info
[i
].kind
= resume_step
;
2691 else if (p
[0] == 'c' || p
[0] == 'C')
2692 resume_info
[i
].kind
= resume_continue
;
2693 else if (p
[0] == 't')
2694 resume_info
[i
].kind
= resume_stop
;
2698 if (p
[0] == 'S' || p
[0] == 'C')
2701 int sig
= strtol (p
+ 1, &q
, 16);
2706 if (!gdb_signal_to_host_p ((enum gdb_signal
) sig
))
2708 resume_info
[i
].sig
= gdb_signal_to_host ((enum gdb_signal
) sig
);
2710 else if (p
[0] == 'r')
2714 p
= unpack_varlen_hex (p
+ 1, &addr
);
2715 resume_info
[i
].step_range_start
= addr
;
2720 p
= unpack_varlen_hex (p
+ 1, &addr
);
2721 resume_info
[i
].step_range_end
= addr
;
2730 resume_info
[i
].thread
= minus_one_ptid
;
2731 default_action
= resume_info
[i
];
2733 /* Note: we don't increment i here, we'll overwrite this entry
2734 the next time through. */
2736 else if (p
[0] == ':')
2739 ptid_t ptid
= read_ptid (p
+ 1, &q
);
2744 if (p
[0] != ';' && p
[0] != 0)
2747 resume_info
[i
].thread
= ptid
;
2754 resume_info
[i
] = default_action
;
2756 resume (resume_info
, n
);
2761 write_enn (own_buf
);
2766 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
2769 resume (struct thread_resume
*actions
, size_t num_actions
)
2771 client_state
&cs
= get_client_state ();
2774 /* Check if among the threads that GDB wants actioned, there's
2775 one with a pending status to report. If so, skip actually
2776 resuming/stopping and report the pending event
2779 thread_info
*thread_with_status
= find_thread ([&] (thread_info
*thread
)
2781 return visit_actioned_threads (thread
, actions
, num_actions
,
2782 handle_pending_status
);
2785 if (thread_with_status
!= NULL
)
2791 the_target
->resume (actions
, num_actions
);
2794 write_ok (cs
.own_buf
);
2797 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
, 0, 1);
2799 if (cs
.last_status
.kind
== TARGET_WAITKIND_NO_RESUMED
2800 && !report_no_resumed
)
2802 /* The client does not support this stop reply. At least
2804 sprintf (cs
.own_buf
, "E.No unwaited-for children left.");
2805 disable_async_io ();
2809 if (cs
.last_status
.kind
!= TARGET_WAITKIND_EXITED
2810 && cs
.last_status
.kind
!= TARGET_WAITKIND_SIGNALLED
2811 && cs
.last_status
.kind
!= TARGET_WAITKIND_NO_RESUMED
)
2812 current_thread
->last_status
= cs
.last_status
;
2814 /* From the client's perspective, all-stop mode always stops all
2815 threads implicitly (and the target backend has already done
2816 so by now). Tag all threads as "want-stopped", so we don't
2817 resume them implicitly without the client telling us to. */
2818 gdb_wants_all_threads_stopped ();
2819 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, &cs
.last_status
);
2820 disable_async_io ();
2822 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
2823 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
2824 target_mourn_inferior (cs
.last_ptid
);
2828 /* Attach to a new program. Return 1 if successful, 0 if failure. */
2830 handle_v_attach (char *own_buf
)
2832 client_state
&cs
= get_client_state ();
2835 pid
= strtol (own_buf
+ 8, NULL
, 16);
2836 if (pid
!= 0 && attach_inferior (pid
) == 0)
2838 /* Don't report shared library events after attaching, even if
2839 some libraries are preloaded. GDB will always poll the
2840 library list. Avoids the "stopped by shared library event"
2841 notice on the GDB side. */
2846 /* In non-stop, we don't send a resume reply. Stop events
2847 will follow up using the normal notification
2852 prepare_resume_reply (own_buf
, cs
.last_ptid
, &cs
.last_status
);
2858 write_enn (own_buf
);
2863 /* Run a new program. Return 1 if successful, 0 if failure. */
2865 handle_v_run (char *own_buf
)
2867 client_state
&cs
= get_client_state ();
2869 std::vector
<char *> new_argv
;
2870 char *new_program_name
= NULL
;
2874 for (p
= own_buf
+ strlen ("vRun;"); p
&& *p
; p
= strchr (p
, ';'))
2880 for (i
= 0, p
= own_buf
+ strlen ("vRun;"); *p
; p
= next_p
, ++i
)
2882 next_p
= strchr (p
, ';');
2884 next_p
= p
+ strlen (p
);
2886 if (i
== 0 && p
== next_p
)
2888 /* No program specified. */
2889 new_program_name
= NULL
;
2891 else if (p
== next_p
)
2893 /* Empty argument. */
2894 new_argv
.push_back (xstrdup (""));
2898 size_t len
= (next_p
- p
) / 2;
2899 /* ARG is the unquoted argument received via the RSP. */
2900 char *arg
= (char *) xmalloc (len
+ 1);
2901 /* FULL_ARGS will contain the quoted version of ARG. */
2902 char *full_arg
= (char *) xmalloc ((len
+ 1) * 2);
2903 /* These are pointers used to navigate the strings above. */
2904 char *tmp_arg
= arg
;
2905 char *tmp_full_arg
= full_arg
;
2908 hex2bin (p
, (gdb_byte
*) arg
, len
);
2911 while (*tmp_arg
!= '\0')
2917 *tmp_full_arg
= '\'';
2923 /* Quote single quote. */
2924 *tmp_full_arg
= '\\';
2932 *tmp_full_arg
= *tmp_arg
;
2938 *tmp_full_arg
++ = '\'';
2940 /* Finish FULL_ARG and push it into the vector containing
2942 *tmp_full_arg
= '\0';
2944 new_program_name
= full_arg
;
2946 new_argv
.push_back (full_arg
);
2953 if (new_program_name
== NULL
)
2955 /* GDB didn't specify a program to run. Use the program from the
2956 last run with the new argument list. */
2957 if (program_path
.get () == NULL
)
2959 write_enn (own_buf
);
2960 free_vector_argv (new_argv
);
2965 program_path
.set (gdb::unique_xmalloc_ptr
<char> (new_program_name
));
2967 /* Free the old argv and install the new one. */
2968 free_vector_argv (program_args
);
2969 program_args
= new_argv
;
2971 target_create_inferior (program_path
.get (), program_args
);
2973 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
2975 prepare_resume_reply (own_buf
, cs
.last_ptid
, &cs
.last_status
);
2977 /* In non-stop, sending a resume reply doesn't set the general
2978 thread, but GDB assumes a vRun sets it (this is so GDB can
2979 query which is the main thread of the new inferior. */
2981 cs
.general_thread
= cs
.last_ptid
;
2987 write_enn (own_buf
);
2992 /* Kill process. Return 1 if successful, 0 if failure. */
2994 handle_v_kill (char *own_buf
)
2996 client_state
&cs
= get_client_state ();
2998 char *p
= &own_buf
[6];
2999 if (cs
.multi_process
)
3000 pid
= strtol (p
, NULL
, 16);
3004 process_info
*proc
= find_process_pid (pid
);
3006 if (proc
!= nullptr && kill_inferior (proc
) == 0)
3008 cs
.last_status
.kind
= TARGET_WAITKIND_SIGNALLED
;
3009 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
3010 cs
.last_ptid
= ptid_t (pid
);
3011 discard_queued_stop_replies (cs
.last_ptid
);
3017 write_enn (own_buf
);
3022 /* Handle all of the extended 'v' packets. */
3024 handle_v_requests (char *own_buf
, int packet_len
, int *new_packet_len
)
3026 client_state
&cs
= get_client_state ();
3027 if (!disable_packet_vCont
)
3029 if (strcmp (own_buf
, "vCtrlC") == 0)
3031 the_target
->request_interrupt ();
3036 if (startswith (own_buf
, "vCont;"))
3038 handle_v_cont (own_buf
);
3042 if (startswith (own_buf
, "vCont?"))
3044 strcpy (own_buf
, "vCont;c;C;t");
3046 if (target_supports_hardware_single_step ()
3047 || target_supports_software_single_step ()
3048 || !cs
.vCont_supported
)
3050 /* If target supports single step either by hardware or by
3051 software, add actions s and S to the list of supported
3052 actions. On the other hand, if GDB doesn't request the
3053 supported vCont actions in qSupported packet, add s and
3054 S to the list too. */
3055 own_buf
= own_buf
+ strlen (own_buf
);
3056 strcpy (own_buf
, ";s;S");
3059 if (target_supports_range_stepping ())
3061 own_buf
= own_buf
+ strlen (own_buf
);
3062 strcpy (own_buf
, ";r");
3068 if (startswith (own_buf
, "vFile:")
3069 && handle_vFile (own_buf
, packet_len
, new_packet_len
))
3072 if (startswith (own_buf
, "vAttach;"))
3074 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3076 fprintf (stderr
, "Already debugging a process\n");
3077 write_enn (own_buf
);
3080 handle_v_attach (own_buf
);
3084 if (startswith (own_buf
, "vRun;"))
3086 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3088 fprintf (stderr
, "Already debugging a process\n");
3089 write_enn (own_buf
);
3092 handle_v_run (own_buf
);
3096 if (startswith (own_buf
, "vKill;"))
3098 if (!target_running ())
3100 fprintf (stderr
, "No process to kill\n");
3101 write_enn (own_buf
);
3104 handle_v_kill (own_buf
);
3108 if (handle_notif_ack (own_buf
, packet_len
))
3111 /* Otherwise we didn't know what packet it was. Say we didn't
3117 /* Resume thread and wait for another event. In non-stop mode,
3118 don't really wait here, but return immediatelly to the event
3121 myresume (char *own_buf
, int step
, int sig
)
3123 client_state
&cs
= get_client_state ();
3124 struct thread_resume resume_info
[2];
3126 int valid_cont_thread
;
3128 valid_cont_thread
= (cs
.cont_thread
!= null_ptid
3129 && cs
.cont_thread
!= minus_one_ptid
);
3131 if (step
|| sig
|| valid_cont_thread
)
3133 resume_info
[0].thread
= current_ptid
;
3135 resume_info
[0].kind
= resume_step
;
3137 resume_info
[0].kind
= resume_continue
;
3138 resume_info
[0].sig
= sig
;
3142 if (!valid_cont_thread
)
3144 resume_info
[n
].thread
= minus_one_ptid
;
3145 resume_info
[n
].kind
= resume_continue
;
3146 resume_info
[n
].sig
= 0;
3150 resume (resume_info
, n
);
3153 /* Callback for for_each_thread. Make a new stop reply for each
3157 queue_stop_reply_callback (thread_info
*thread
)
3159 /* For now, assume targets that don't have this callback also don't
3160 manage the thread's last_status field. */
3161 if (!the_target
->supports_thread_stopped ())
3163 struct vstop_notif
*new_notif
= new struct vstop_notif
;
3165 new_notif
->ptid
= thread
->id
;
3166 new_notif
->status
= thread
->last_status
;
3167 /* Pass the last stop reply back to GDB, but don't notify
3169 notif_event_enque (¬if_stop
, new_notif
);
3173 if (target_thread_stopped (thread
))
3177 std::string status_string
3178 = target_waitstatus_to_string (&thread
->last_status
);
3180 debug_printf ("Reporting thread %s as already stopped with %s\n",
3181 target_pid_to_str (thread
->id
),
3182 status_string
.c_str ());
3185 gdb_assert (thread
->last_status
.kind
!= TARGET_WAITKIND_IGNORE
);
3187 /* Pass the last stop reply back to GDB, but don't notify
3189 queue_stop_reply (thread
->id
, &thread
->last_status
);
3194 /* Set this inferior threads's state as "want-stopped". We won't
3195 resume this thread until the client gives us another action for
3199 gdb_wants_thread_stopped (thread_info
*thread
)
3201 thread
->last_resume_kind
= resume_stop
;
3203 if (thread
->last_status
.kind
== TARGET_WAITKIND_IGNORE
)
3205 /* Most threads are stopped implicitly (all-stop); tag that with
3207 thread
->last_status
.kind
= TARGET_WAITKIND_STOPPED
;
3208 thread
->last_status
.value
.sig
= GDB_SIGNAL_0
;
3212 /* Set all threads' states as "want-stopped". */
3215 gdb_wants_all_threads_stopped (void)
3217 for_each_thread (gdb_wants_thread_stopped
);
3220 /* Callback for for_each_thread. If the thread is stopped with an
3221 interesting event, mark it as having a pending event. */
3224 set_pending_status_callback (thread_info
*thread
)
3226 if (thread
->last_status
.kind
!= TARGET_WAITKIND_STOPPED
3227 || (thread
->last_status
.value
.sig
!= GDB_SIGNAL_0
3228 /* A breakpoint, watchpoint or finished step from a previous
3229 GDB run isn't considered interesting for a new GDB run.
3230 If we left those pending, the new GDB could consider them
3231 random SIGTRAPs. This leaves out real async traps. We'd
3232 have to peek into the (target-specific) siginfo to
3233 distinguish those. */
3234 && thread
->last_status
.value
.sig
!= GDB_SIGNAL_TRAP
))
3235 thread
->status_pending_p
= 1;
3238 /* Status handler for the '?' packet. */
3241 handle_status (char *own_buf
)
3243 client_state
&cs
= get_client_state ();
3245 /* GDB is connected, don't forward events to the target anymore. */
3246 for_each_process ([] (process_info
*process
) {
3247 process
->gdb_detached
= 0;
3250 /* In non-stop mode, we must send a stop reply for each stopped
3251 thread. In all-stop mode, just send one for the first stopped
3256 for_each_thread (queue_stop_reply_callback
);
3258 /* The first is sent immediatly. OK is sent if there is no
3259 stopped thread, which is the same handling of the vStopped
3260 packet (by design). */
3261 notif_write_event (¬if_stop
, cs
.own_buf
);
3265 thread_info
*thread
= NULL
;
3267 target_pause_all (false);
3268 target_stabilize_threads ();
3269 gdb_wants_all_threads_stopped ();
3271 /* We can only report one status, but we might be coming out of
3272 non-stop -- if more than one thread is stopped with
3273 interesting events, leave events for the threads we're not
3274 reporting now pending. They'll be reported the next time the
3275 threads are resumed. Start by marking all interesting events
3277 for_each_thread (set_pending_status_callback
);
3279 /* Prefer the last thread that reported an event to GDB (even if
3280 that was a GDB_SIGNAL_TRAP). */
3281 if (cs
.last_status
.kind
!= TARGET_WAITKIND_IGNORE
3282 && cs
.last_status
.kind
!= TARGET_WAITKIND_EXITED
3283 && cs
.last_status
.kind
!= TARGET_WAITKIND_SIGNALLED
)
3284 thread
= find_thread_ptid (cs
.last_ptid
);
3286 /* If the last event thread is not found for some reason, look
3287 for some other thread that might have an event to report. */
3289 thread
= find_thread ([] (thread_info
*thr_arg
)
3291 return thr_arg
->status_pending_p
;
3294 /* If we're still out of luck, simply pick the first thread in
3297 thread
= get_first_thread ();
3301 struct thread_info
*tp
= (struct thread_info
*) thread
;
3303 /* We're reporting this event, so it's no longer
3305 tp
->status_pending_p
= 0;
3307 /* GDB assumes the current thread is the thread we're
3308 reporting the status for. */
3309 cs
.general_thread
= thread
->id
;
3310 set_desired_thread ();
3312 gdb_assert (tp
->last_status
.kind
!= TARGET_WAITKIND_IGNORE
);
3313 prepare_resume_reply (own_buf
, tp
->id
, &tp
->last_status
);
3316 strcpy (own_buf
, "W00");
3321 gdbserver_version (void)
3323 printf ("GNU gdbserver %s%s\n"
3324 "Copyright (C) 2020 Free Software Foundation, Inc.\n"
3325 "gdbserver is free software, covered by the "
3326 "GNU General Public License.\n"
3327 "This gdbserver was configured as \"%s\"\n",
3328 PKGVERSION
, version
, host_name
);
3332 gdbserver_usage (FILE *stream
)
3334 fprintf (stream
, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3335 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3336 "\tgdbserver [OPTIONS] --multi COMM\n"
3338 "COMM may either be a tty device (for serial debugging),\n"
3339 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3340 "stdin/stdout of gdbserver.\n"
3341 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3342 "PID is the process ID to attach to, when --attach is specified.\n"
3344 "Operating modes:\n"
3346 " --attach Attach to running process PID.\n"
3347 " --multi Start server without a specific program, and\n"
3348 " only quit when explicitly commanded.\n"
3349 " --once Exit after the first connection has closed.\n"
3350 " --help Print this message and then exit.\n"
3351 " --version Display version information and exit.\n"
3355 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3356 " --disable-randomization\n"
3357 " Run PROG with address space randomization disabled.\n"
3358 " --no-disable-randomization\n"
3359 " Don't disable address space randomization when\n"
3361 " --startup-with-shell\n"
3362 " Start PROG using a shell. I.e., execs a shell that\n"
3363 " then execs PROG. (default)\n"
3364 " --no-startup-with-shell\n"
3365 " Exec PROG directly instead of using a shell.\n"
3366 " Disables argument globbing and variable substitution\n"
3367 " on UNIX-like systems.\n"
3371 " --debug Enable general debugging output.\n"
3372 " --debug-format=OPT1[,OPT2,...]\n"
3373 " Specify extra content in debugging output.\n"
3378 " --remote-debug Enable remote protocol debugging output.\n"
3379 " --event-loop-debug Enable event loop debugging output.\n"
3380 " --disable-packet=OPT1[,OPT2,...]\n"
3381 " Disable support for RSP packets or features.\n"
3383 " vCont, T, Tthread, qC, qfThreadInfo and \n"
3384 " threads (disable all threading packets).\n"
3386 "For more information, consult the GDB manual (available as on-line \n"
3387 "info or a printed manual).\n");
3388 if (REPORT_BUGS_TO
[0] && stream
== stdout
)
3389 fprintf (stream
, "Report bugs to \"%s\".\n", REPORT_BUGS_TO
);
3393 gdbserver_show_disableable (FILE *stream
)
3395 fprintf (stream
, "Disableable packets:\n"
3396 " vCont \tAll vCont packets\n"
3397 " qC \tQuerying the current thread\n"
3398 " qfThreadInfo\tThread listing\n"
3399 " Tthread \tPassing the thread specifier in the "
3400 "T stop reply packet\n"
3401 " threads \tAll of the above\n"
3402 " T \tAll 'T' packets\n");
3405 /* Start up the event loop. This is the entry point to the event
3411 /* Loop until there is nothing to do. This is the entry point to
3412 the event loop engine. If nothing is ready at this time, wait
3413 for something to happen (via wait_for_event), then process it.
3414 Return when there are no longer event sources to wait for. */
3416 keep_processing_events
= true;
3417 while (keep_processing_events
)
3419 /* Any events already waiting in the queue? */
3420 int res
= gdb_do_one_event ();
3422 /* Was there an error? */
3427 /* We are done with the event loop. There are no more event sources
3428 to listen to. So we exit gdbserver. */
3432 kill_inferior_callback (process_info
*process
)
3434 kill_inferior (process
);
3435 discard_queued_stop_replies (ptid_t (process
->pid
));
3438 /* Call this when exiting gdbserver with possible inferiors that need
3439 to be killed or detached from. */
3442 detach_or_kill_for_exit (void)
3444 /* First print a list of the inferiors we will be killing/detaching.
3445 This is to assist the user, for example, in case the inferior unexpectedly
3446 dies after we exit: did we screw up or did the inferior exit on its own?
3447 Having this info will save some head-scratching. */
3449 if (have_started_inferiors_p ())
3451 fprintf (stderr
, "Killing process(es):");
3453 for_each_process ([] (process_info
*process
) {
3454 if (!process
->attached
)
3455 fprintf (stderr
, " %d", process
->pid
);
3458 fprintf (stderr
, "\n");
3460 if (have_attached_inferiors_p ())
3462 fprintf (stderr
, "Detaching process(es):");
3464 for_each_process ([] (process_info
*process
) {
3465 if (process
->attached
)
3466 fprintf (stderr
, " %d", process
->pid
);
3469 fprintf (stderr
, "\n");
3472 /* Now we can kill or detach the inferiors. */
3473 for_each_process ([] (process_info
*process
) {
3474 int pid
= process
->pid
;
3476 if (process
->attached
)
3477 detach_inferior (process
);
3479 kill_inferior (process
);
3481 discard_queued_stop_replies (ptid_t (pid
));
3485 /* Value that will be passed to exit(3) when gdbserver exits. */
3486 static int exit_code
;
3488 /* Wrapper for detach_or_kill_for_exit that catches and prints
3492 detach_or_kill_for_exit_cleanup ()
3496 detach_or_kill_for_exit ();
3498 catch (const gdb_exception
&exception
)
3501 fprintf (stderr
, "Detach or kill failed: %s\n",
3507 /* Main function. This is called by the real "main" function,
3508 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
3510 static void ATTRIBUTE_NORETURN
3511 captured_main (int argc
, char *argv
[])
3516 const char *port
= NULL
;
3517 char **next_arg
= &argv
[1];
3518 volatile int multi_mode
= 0;
3519 volatile int attach
= 0;
3521 bool selftest
= false;
3523 std::vector
<const char *> selftest_filters
;
3526 current_directory
= getcwd (NULL
, 0);
3527 client_state
&cs
= get_client_state ();
3529 if (current_directory
== NULL
)
3531 error (_("Could not find current working directory: %s"),
3532 safe_strerror (errno
));
3535 while (*next_arg
!= NULL
&& **next_arg
== '-')
3537 if (strcmp (*next_arg
, "--version") == 0)
3539 gdbserver_version ();
3542 else if (strcmp (*next_arg
, "--help") == 0)
3544 gdbserver_usage (stdout
);
3547 else if (strcmp (*next_arg
, "--attach") == 0)
3549 else if (strcmp (*next_arg
, "--multi") == 0)
3551 else if (strcmp (*next_arg
, "--wrapper") == 0)
3558 while (*next_arg
!= NULL
&& strcmp (*next_arg
, "--") != 0)
3560 wrapper_argv
+= *next_arg
;
3561 wrapper_argv
+= ' ';
3565 if (!wrapper_argv
.empty ())
3567 /* Erase the last whitespace. */
3568 wrapper_argv
.erase (wrapper_argv
.end () - 1);
3571 if (next_arg
== tmp
|| *next_arg
== NULL
)
3573 gdbserver_usage (stderr
);
3577 /* Consume the "--". */
3580 else if (strcmp (*next_arg
, "--debug") == 0)
3582 else if (startswith (*next_arg
, "--debug-format="))
3584 std::string error_msg
3585 = parse_debug_format_options ((*next_arg
)
3586 + sizeof ("--debug-format=") - 1, 0);
3588 if (!error_msg
.empty ())
3590 fprintf (stderr
, "%s", error_msg
.c_str ());
3594 else if (strcmp (*next_arg
, "--remote-debug") == 0)
3596 else if (strcmp (*next_arg
, "--event-loop-debug") == 0)
3597 debug_event_loop
= debug_event_loop_kind::ALL
;
3598 else if (startswith (*next_arg
, "--debug-file="))
3599 debug_set_output ((*next_arg
) + sizeof ("--debug-file=") -1);
3600 else if (strcmp (*next_arg
, "--disable-packet") == 0)
3602 gdbserver_show_disableable (stdout
);
3605 else if (startswith (*next_arg
, "--disable-packet="))
3607 char *packets
= *next_arg
+= sizeof ("--disable-packet=") - 1;
3609 for (char *tok
= strtok_r (packets
, ",", &saveptr
);
3611 tok
= strtok_r (NULL
, ",", &saveptr
))
3613 if (strcmp ("vCont", tok
) == 0)
3614 disable_packet_vCont
= true;
3615 else if (strcmp ("Tthread", tok
) == 0)
3616 disable_packet_Tthread
= true;
3617 else if (strcmp ("qC", tok
) == 0)
3618 disable_packet_qC
= true;
3619 else if (strcmp ("qfThreadInfo", tok
) == 0)
3620 disable_packet_qfThreadInfo
= true;
3621 else if (strcmp ("T", tok
) == 0)
3622 disable_packet_T
= true;
3623 else if (strcmp ("threads", tok
) == 0)
3625 disable_packet_vCont
= true;
3626 disable_packet_Tthread
= true;
3627 disable_packet_qC
= true;
3628 disable_packet_qfThreadInfo
= true;
3632 fprintf (stderr
, "Don't know how to disable \"%s\".\n\n",
3634 gdbserver_show_disableable (stderr
);
3639 else if (strcmp (*next_arg
, "-") == 0)
3641 /* "-" specifies a stdio connection and is a form of port
3643 port
= STDIO_CONNECTION_NAME
;
3647 else if (strcmp (*next_arg
, "--disable-randomization") == 0)
3648 cs
.disable_randomization
= 1;
3649 else if (strcmp (*next_arg
, "--no-disable-randomization") == 0)
3650 cs
.disable_randomization
= 0;
3651 else if (strcmp (*next_arg
, "--startup-with-shell") == 0)
3652 startup_with_shell
= true;
3653 else if (strcmp (*next_arg
, "--no-startup-with-shell") == 0)
3654 startup_with_shell
= false;
3655 else if (strcmp (*next_arg
, "--once") == 0)
3657 else if (strcmp (*next_arg
, "--selftest") == 0)
3659 else if (startswith (*next_arg
, "--selftest="))
3664 const char *filter
= *next_arg
+ strlen ("--selftest=");
3665 if (*filter
== '\0')
3667 fprintf (stderr
, _("Error: selftest filter is empty.\n"));
3671 selftest_filters
.push_back (filter
);
3676 fprintf (stderr
, "Unknown argument: %s\n", *next_arg
);
3689 if ((port
== NULL
|| (!attach
&& !multi_mode
&& *next_arg
== NULL
))
3692 gdbserver_usage (stderr
);
3696 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
3697 opened by remote_prepare. */
3700 save_original_signals_state (false);
3702 /* We need to know whether the remote connection is stdio before
3703 starting the inferior. Inferiors created in this scenario have
3704 stdin,stdout redirected. So do this here before we call
3707 remote_prepare (port
);
3712 /* --attach used to come after PORT, so allow it there for
3714 if (*next_arg
!= NULL
&& strcmp (*next_arg
, "--attach") == 0)
3721 && (*next_arg
== NULL
3722 || (*next_arg
)[0] == '\0'
3723 || (pid
= strtoul (*next_arg
, &arg_end
, 0)) == 0
3725 || next_arg
[1] != NULL
))
3730 gdbserver_usage (stderr
);
3734 /* Gather information about the environment. */
3735 our_environ
= gdb_environ::from_host_environ ();
3737 initialize_async_io ();
3739 have_job_control ();
3740 if (target_supports_tracepoints ())
3741 initialize_tracepoint ();
3743 mem_buf
= (unsigned char *) xmalloc (PBUFSIZ
);
3748 selftests::run_tests (selftest_filters
);
3750 printf (_("Selftests have been disabled for this build.\n"));
3752 throw_quit ("Quit");
3755 if (pid
== 0 && *next_arg
!= NULL
)
3759 n
= argc
- (next_arg
- argv
);
3760 program_path
.set (make_unique_xstrdup (next_arg
[0]));
3761 for (i
= 1; i
< n
; i
++)
3762 program_args
.push_back (xstrdup (next_arg
[i
]));
3764 /* Wait till we are at first instruction in program. */
3765 target_create_inferior (program_path
.get (), program_args
);
3767 /* We are now (hopefully) stopped at the first instruction of
3768 the target process. This assumes that the target process was
3769 successfully created. */
3773 if (attach_inferior (pid
) == -1)
3774 error ("Attaching not supported on this target");
3776 /* Otherwise succeeded. */
3780 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
3781 cs
.last_status
.value
.integer
= 0;
3782 cs
.last_ptid
= minus_one_ptid
;
3785 SCOPE_EXIT
{ detach_or_kill_for_exit_cleanup (); };
3787 /* Don't report shared library events on the initial connection,
3788 even if some libraries are preloaded. Avoids the "stopped by
3789 shared library event" notice on gdb side. */
3792 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
3793 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
3798 if (!was_running
&& !multi_mode
)
3799 error ("No program to debug");
3804 cs
.multi_process
= 0;
3805 cs
.report_fork_events
= 0;
3806 cs
.report_vfork_events
= 0;
3807 cs
.report_exec_events
= 0;
3808 /* Be sure we're out of tfind mode. */
3809 cs
.current_traceframe
= -1;
3810 cs
.cont_thread
= null_ptid
;
3811 cs
.swbreak_feature
= 0;
3812 cs
.hwbreak_feature
= 0;
3813 cs
.vCont_supported
= 0;
3819 /* Wait for events. This will return when all event sources
3820 are removed from the event loop. */
3821 start_event_loop ();
3823 /* If an exit was requested (using the "monitor exit"
3824 command), terminate now. */
3826 throw_quit ("Quit");
3828 /* The only other way to get here is for getpkt to fail:
3830 - If --once was specified, we're done.
3832 - If not in extended-remote mode, and we're no longer
3833 debugging anything, simply exit: GDB has disconnected
3834 after processing the last process exit.
3836 - Otherwise, close the connection and reopen it at the
3838 if (run_once
|| (!extended_protocol
&& !target_running ()))
3839 throw_quit ("Quit");
3842 "Remote side has terminated connection. "
3843 "GDBserver will reopen the connection.\n");
3845 /* Get rid of any pending statuses. An eventual reconnection
3846 (by the same GDB instance or another) will refresh all its
3847 state from scratch. */
3848 discard_queued_stop_replies (minus_one_ptid
);
3849 for_each_thread ([] (thread_info
*thread
)
3851 thread
->status_pending_p
= 0;
3856 if (disconnected_tracing
)
3858 /* Try to enable non-stop/async mode, so we we can
3859 both wait for an async socket accept, and handle
3860 async target events simultaneously. There's also
3861 no point either in having the target always stop
3862 all threads, when we're going to pass signals
3863 down without informing GDB. */
3866 if (the_target
->start_non_stop (true))
3869 /* Detaching implicitly resumes all threads;
3870 simply disconnecting does not. */
3876 "Disconnected tracing disabled; "
3877 "stopping trace run.\n");
3882 catch (const gdb_exception_error
&exception
)
3885 fprintf (stderr
, "gdbserver: %s\n", exception
.what ());
3887 if (response_needed
)
3889 write_enn (cs
.own_buf
);
3890 putpkt (cs
.own_buf
);
3894 throw_quit ("Quit");
3899 /* Main function. */
3902 main (int argc
, char *argv
[])
3907 captured_main (argc
, argv
);
3909 catch (const gdb_exception
&exception
)
3911 if (exception
.reason
== RETURN_ERROR
)
3914 fprintf (stderr
, "%s\n", exception
.what ());
3915 fprintf (stderr
, "Exiting\n");
3922 gdb_assert_not_reached ("captured_main should never return");
3925 /* Process options coming from Z packets for a breakpoint. PACKET is
3926 the packet buffer. *PACKET is updated to point to the first char
3927 after the last processed option. */
3930 process_point_options (struct gdb_breakpoint
*bp
, const char **packet
)
3932 const char *dataptr
= *packet
;
3935 /* Check if data has the correct format. */
3936 if (*dataptr
!= ';')
3943 if (*dataptr
== ';')
3946 if (*dataptr
== 'X')
3948 /* Conditional expression. */
3950 debug_printf ("Found breakpoint condition.\n");
3951 if (!add_breakpoint_condition (bp
, &dataptr
))
3952 dataptr
= strchrnul (dataptr
, ';');
3954 else if (startswith (dataptr
, "cmds:"))
3956 dataptr
+= strlen ("cmds:");
3958 debug_printf ("Found breakpoint commands %s.\n", dataptr
);
3959 persist
= (*dataptr
== '1');
3961 if (add_breakpoint_commands (bp
, &dataptr
, persist
))
3962 dataptr
= strchrnul (dataptr
, ';');
3966 fprintf (stderr
, "Unknown token %c, ignoring.\n",
3968 /* Skip tokens until we find one that we recognize. */
3969 dataptr
= strchrnul (dataptr
, ';');
3975 /* Event loop callback that handles a serial event. The first byte in
3976 the serial buffer gets us here. We expect characters to arrive at
3977 a brisk pace, so we read the rest of the packet with a blocking
3981 process_serial_event (void)
3983 client_state
&cs
= get_client_state ();
3989 int new_packet_len
= -1;
3991 disable_async_io ();
3993 response_needed
= false;
3994 packet_len
= getpkt (cs
.own_buf
);
3995 if (packet_len
<= 0)
3998 /* Force an event loop break. */
4001 response_needed
= true;
4003 char ch
= cs
.own_buf
[0];
4007 handle_query (cs
.own_buf
, packet_len
, &new_packet_len
);
4010 handle_general_set (cs
.own_buf
);
4013 handle_detach (cs
.own_buf
);
4016 extended_protocol
= true;
4017 write_ok (cs
.own_buf
);
4020 handle_status (cs
.own_buf
);
4023 if (cs
.own_buf
[1] == 'c' || cs
.own_buf
[1] == 'g' || cs
.own_buf
[1] == 's')
4025 require_running_or_break (cs
.own_buf
);
4027 ptid_t thread_id
= read_ptid (&cs
.own_buf
[2], NULL
);
4029 if (thread_id
== null_ptid
|| thread_id
== minus_one_ptid
)
4030 thread_id
= null_ptid
;
4031 else if (thread_id
.is_pid ())
4033 /* The ptid represents a pid. */
4034 thread_info
*thread
= find_any_thread_of_pid (thread_id
.pid ());
4038 write_enn (cs
.own_buf
);
4042 thread_id
= thread
->id
;
4046 /* The ptid represents a lwp/tid. */
4047 if (find_thread_ptid (thread_id
) == NULL
)
4049 write_enn (cs
.own_buf
);
4054 if (cs
.own_buf
[1] == 'g')
4056 if (thread_id
== null_ptid
)
4058 /* GDB is telling us to choose any thread. Check if
4059 the currently selected thread is still valid. If
4060 it is not, select the first available. */
4061 thread_info
*thread
= find_thread_ptid (cs
.general_thread
);
4063 thread
= get_first_thread ();
4064 thread_id
= thread
->id
;
4067 cs
.general_thread
= thread_id
;
4068 set_desired_thread ();
4069 gdb_assert (current_thread
!= NULL
);
4071 else if (cs
.own_buf
[1] == 'c')
4072 cs
.cont_thread
= thread_id
;
4074 write_ok (cs
.own_buf
);
4078 /* Silently ignore it so that gdb can extend the protocol
4079 without compatibility headaches. */
4080 cs
.own_buf
[0] = '\0';
4084 require_running_or_break (cs
.own_buf
);
4085 if (cs
.current_traceframe
>= 0)
4087 struct regcache
*regcache
4088 = new_register_cache (current_target_desc ());
4090 if (fetch_traceframe_registers (cs
.current_traceframe
,
4092 registers_to_string (regcache
, cs
.own_buf
);
4094 write_enn (cs
.own_buf
);
4095 free_register_cache (regcache
);
4099 struct regcache
*regcache
;
4101 if (!set_desired_thread ())
4102 write_enn (cs
.own_buf
);
4105 regcache
= get_thread_regcache (current_thread
, 1);
4106 registers_to_string (regcache
, cs
.own_buf
);
4111 require_running_or_break (cs
.own_buf
);
4112 if (cs
.current_traceframe
>= 0)
4113 write_enn (cs
.own_buf
);
4116 struct regcache
*regcache
;
4118 if (!set_desired_thread ())
4119 write_enn (cs
.own_buf
);
4122 regcache
= get_thread_regcache (current_thread
, 1);
4123 registers_from_string (regcache
, &cs
.own_buf
[1]);
4124 write_ok (cs
.own_buf
);
4130 require_running_or_break (cs
.own_buf
);
4131 decode_m_packet (&cs
.own_buf
[1], &mem_addr
, &len
);
4132 int res
= gdb_read_memory (mem_addr
, mem_buf
, len
);
4134 write_enn (cs
.own_buf
);
4136 bin2hex (mem_buf
, cs
.own_buf
, res
);
4140 require_running_or_break (cs
.own_buf
);
4141 decode_M_packet (&cs
.own_buf
[1], &mem_addr
, &len
, &mem_buf
);
4142 if (gdb_write_memory (mem_addr
, mem_buf
, len
) == 0)
4143 write_ok (cs
.own_buf
);
4145 write_enn (cs
.own_buf
);
4148 require_running_or_break (cs
.own_buf
);
4149 if (decode_X_packet (&cs
.own_buf
[1], packet_len
- 1,
4150 &mem_addr
, &len
, &mem_buf
) < 0
4151 || gdb_write_memory (mem_addr
, mem_buf
, len
) != 0)
4152 write_enn (cs
.own_buf
);
4154 write_ok (cs
.own_buf
);
4157 require_running_or_break (cs
.own_buf
);
4158 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4159 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4160 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4163 myresume (cs
.own_buf
, 0, signal
);
4166 require_running_or_break (cs
.own_buf
);
4167 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4168 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4169 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4172 myresume (cs
.own_buf
, 1, signal
);
4175 require_running_or_break (cs
.own_buf
);
4177 myresume (cs
.own_buf
, 0, signal
);
4180 require_running_or_break (cs
.own_buf
);
4182 myresume (cs
.own_buf
, 1, signal
);
4184 case 'Z': /* insert_ ... */
4186 case 'z': /* remove_ ... */
4191 char type
= cs
.own_buf
[1];
4193 const int insert
= ch
== 'Z';
4194 const char *p
= &cs
.own_buf
[3];
4196 p
= unpack_varlen_hex (p
, &addr
);
4197 kind
= strtol (p
+ 1, &dataptr
, 16);
4201 struct gdb_breakpoint
*bp
;
4203 bp
= set_gdb_breakpoint (type
, addr
, kind
, &res
);
4208 /* GDB may have sent us a list of *point parameters to
4209 be evaluated on the target's side. Read such list
4210 here. If we already have a list of parameters, GDB
4211 is telling us to drop that list and use this one
4213 clear_breakpoint_conditions_and_commands (bp
);
4214 const char *options
= dataptr
;
4215 process_point_options (bp
, &options
);
4219 res
= delete_gdb_breakpoint (type
, addr
, kind
);
4222 write_ok (cs
.own_buf
);
4225 cs
.own_buf
[0] = '\0';
4227 write_enn (cs
.own_buf
);
4231 response_needed
= false;
4232 if (!target_running ())
4233 /* The packet we received doesn't make sense - but we can't
4234 reply to it, either. */
4237 fprintf (stderr
, "Killing all inferiors\n");
4239 for_each_process (kill_inferior_callback
);
4241 /* When using the extended protocol, we wait with no program
4242 running. The traditional protocol will exit instead. */
4243 if (extended_protocol
)
4245 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
4246 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
4254 require_running_or_break (cs
.own_buf
);
4256 ptid_t thread_id
= read_ptid (&cs
.own_buf
[1], NULL
);
4257 if (find_thread_ptid (thread_id
) == NULL
)
4259 write_enn (cs
.own_buf
);
4263 if (mythread_alive (thread_id
))
4264 write_ok (cs
.own_buf
);
4266 write_enn (cs
.own_buf
);
4270 response_needed
= false;
4272 /* Restarting the inferior is only supported in the extended
4274 if (extended_protocol
)
4276 if (target_running ())
4277 for_each_process (kill_inferior_callback
);
4279 fprintf (stderr
, "GDBserver restarting\n");
4281 /* Wait till we are at 1st instruction in prog. */
4282 if (program_path
.get () != NULL
)
4284 target_create_inferior (program_path
.get (), program_args
);
4286 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
4288 /* Stopped at the first instruction of the target
4290 cs
.general_thread
= cs
.last_ptid
;
4294 /* Something went wrong. */
4295 cs
.general_thread
= null_ptid
;
4300 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
4301 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
4307 /* It is a request we don't understand. Respond with an
4308 empty packet so that gdb knows that we don't support this
4310 cs
.own_buf
[0] = '\0';
4314 /* Extended (long) request. */
4315 handle_v_requests (cs
.own_buf
, packet_len
, &new_packet_len
);
4319 /* It is a request we don't understand. Respond with an empty
4320 packet so that gdb knows that we don't support this
4322 cs
.own_buf
[0] = '\0';
4326 if (new_packet_len
!= -1)
4327 putpkt_binary (cs
.own_buf
, new_packet_len
);
4329 putpkt (cs
.own_buf
);
4331 response_needed
= false;
4339 /* Event-loop callback for serial events. */
4342 handle_serial_event (int err
, gdb_client_data client_data
)
4345 debug_printf ("handling possible serial event\n");
4347 /* Really handle it. */
4348 if (process_serial_event () < 0)
4350 keep_processing_events
= false;
4354 /* Be sure to not change the selected thread behind GDB's back.
4355 Important in the non-stop mode asynchronous protocol. */
4356 set_desired_thread ();
4359 /* Push a stop notification on the notification queue. */
4362 push_stop_notification (ptid_t ptid
, struct target_waitstatus
*status
)
4364 struct vstop_notif
*vstop_notif
= new struct vstop_notif
;
4366 vstop_notif
->status
= *status
;
4367 vstop_notif
->ptid
= ptid
;
4368 /* Push Stop notification. */
4369 notif_push (¬if_stop
, vstop_notif
);
4372 /* Event-loop callback for target events. */
4375 handle_target_event (int err
, gdb_client_data client_data
)
4377 client_state
&cs
= get_client_state ();
4379 debug_printf ("handling possible target event\n");
4381 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
,
4384 if (cs
.last_status
.kind
== TARGET_WAITKIND_NO_RESUMED
)
4386 if (gdb_connected () && report_no_resumed
)
4387 push_stop_notification (null_ptid
, &cs
.last_status
);
4389 else if (cs
.last_status
.kind
!= TARGET_WAITKIND_IGNORE
)
4391 int pid
= cs
.last_ptid
.pid ();
4392 struct process_info
*process
= find_process_pid (pid
);
4393 int forward_event
= !gdb_connected () || process
->gdb_detached
;
4395 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
4396 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
4398 mark_breakpoints_out (process
);
4399 target_mourn_inferior (cs
.last_ptid
);
4401 else if (cs
.last_status
.kind
== TARGET_WAITKIND_THREAD_EXITED
)
4405 /* We're reporting this thread as stopped. Update its
4406 "want-stopped" state to what the client wants, until it
4407 gets a new resume action. */
4408 current_thread
->last_resume_kind
= resume_stop
;
4409 current_thread
->last_status
= cs
.last_status
;
4414 if (!target_running ())
4416 /* The last process exited. We're done. */
4420 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
4421 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
4422 || cs
.last_status
.kind
== TARGET_WAITKIND_THREAD_EXITED
)
4426 /* A thread stopped with a signal, but gdb isn't
4427 connected to handle it. Pass it down to the
4428 inferior, as if it wasn't being traced. */
4429 enum gdb_signal signal
;
4432 debug_printf ("GDB not connected; forwarding event %d for"
4434 (int) cs
.last_status
.kind
,
4435 target_pid_to_str (cs
.last_ptid
));
4437 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
4438 signal
= cs
.last_status
.value
.sig
;
4440 signal
= GDB_SIGNAL_0
;
4441 target_continue (cs
.last_ptid
, signal
);
4445 push_stop_notification (cs
.last_ptid
, &cs
.last_status
);
4448 /* Be sure to not change the selected thread behind GDB's back.
4449 Important in the non-stop mode asynchronous protocol. */
4450 set_desired_thread ();
4453 /* See gdbsupport/event-loop.h. */
4456 invoke_async_signal_handlers ()
4461 /* See gdbsupport/event-loop.h. */
4464 check_async_event_handlers ()
4469 /* See gdbsupport/errors.h */
4478 /* See gdbsupport/gdb_select.h. */
4481 gdb_select (int n
, fd_set
*readfds
, fd_set
*writefds
,
4482 fd_set
*exceptfds
, struct timeval
*timeout
)
4484 return select (n
, readfds
, writefds
, exceptfds
, timeout
);
4495 } // namespace selftests
4496 #endif /* GDB_SELF_TEST */