1 /* Main code for remote server for GDB.
2 Copyright (C) 1989-2022 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 /* The environment to pass to the inferior when creating it. */
70 static gdb_environ our_environ
;
74 static bool extended_protocol
;
75 static bool response_needed
;
76 static bool exit_requested
;
78 /* --once: Exit after the first connection has closed. */
81 /* Whether to report TARGET_WAITKIND_NO_RESUMED events. */
82 static bool report_no_resumed
;
84 /* The event loop checks this to decide whether to continue accepting
86 static bool keep_processing_events
= true;
91 /* Set the PROGRAM_PATH. Here we adjust the path of the provided
93 void set (const char *path
)
97 /* Make sure we're using the absolute path of the inferior when
99 if (!contains_dir_separator (m_path
.c_str ()))
103 /* Check if the file is in our CWD. If it is, then we prefix
104 its name with CURRENT_DIRECTORY. Otherwise, we leave the
105 name as-is because we'll try searching for it in $PATH. */
106 if (is_regular_file (m_path
.c_str (), ®_file_errno
))
107 m_path
= gdb_abspath (m_path
.c_str ());
111 /* Return the PROGRAM_PATH. */
113 { return m_path
.empty () ? nullptr : m_path
.c_str (); }
116 /* The program name, adjusted if needed. */
119 static std::vector
<char *> program_args
;
120 static std::string wrapper_argv
;
122 /* The PID of the originally created or attached inferior. Used to
123 send signals to the process when GDB sends us an asynchronous interrupt
124 (user hitting Control-C in the client), and to wait for the child to exit
125 when no longer debugging it. */
127 unsigned long signal_pid
;
129 /* Set if you want to disable optional thread related packets support
130 in gdbserver, for the sake of testing GDB against stubs that don't
132 bool disable_packet_vCont
;
133 bool disable_packet_Tthread
;
134 bool disable_packet_qC
;
135 bool disable_packet_qfThreadInfo
;
136 bool disable_packet_T
;
138 static unsigned char *mem_buf
;
140 /* A sub-class of 'struct notif_event' for stop, holding information
141 relative to a single stop reply. We keep a queue of these to
142 push to GDB in non-stop mode. */
144 struct vstop_notif
: public notif_event
146 /* Thread or process that got the event. */
150 struct target_waitstatus status
;
153 /* The current btrace configuration. This is gdbserver's mirror of GDB's
154 btrace configuration. */
155 static struct btrace_config current_btrace_conf
;
157 /* The client remote protocol state. */
159 static client_state g_client_state
;
164 client_state
&cs
= g_client_state
;
169 /* Put a stop reply to the stop reply queue. */
172 queue_stop_reply (ptid_t ptid
, const target_waitstatus
&status
)
174 struct vstop_notif
*new_notif
= new struct vstop_notif
;
176 new_notif
->ptid
= ptid
;
177 new_notif
->status
= status
;
179 notif_event_enque (¬if_stop
, new_notif
);
183 remove_all_on_match_ptid (struct notif_event
*event
, ptid_t filter_ptid
)
185 struct vstop_notif
*vstop_event
= (struct vstop_notif
*) event
;
187 return vstop_event
->ptid
.matches (filter_ptid
);
193 discard_queued_stop_replies (ptid_t ptid
)
195 std::list
<notif_event
*>::iterator iter
, next
, end
;
196 end
= notif_stop
.queue
.end ();
197 for (iter
= notif_stop
.queue
.begin (); iter
!= end
; iter
= next
)
202 if (iter
== notif_stop
.queue
.begin ())
204 /* The head of the list contains the notification that was
205 already sent to GDB. So we can't remove it, otherwise
206 when GDB sends the vStopped, it would ack the _next_
207 notification, which hadn't been sent yet! */
211 if (remove_all_on_match_ptid (*iter
, ptid
))
214 notif_stop
.queue
.erase (iter
);
220 vstop_notif_reply (struct notif_event
*event
, char *own_buf
)
222 struct vstop_notif
*vstop
= (struct vstop_notif
*) event
;
224 prepare_resume_reply (own_buf
, vstop
->ptid
, vstop
->status
);
227 /* Helper for in_queued_stop_replies. */
230 in_queued_stop_replies_ptid (struct notif_event
*event
, ptid_t filter_ptid
)
232 struct vstop_notif
*vstop_event
= (struct vstop_notif
*) event
;
234 if (vstop_event
->ptid
.matches (filter_ptid
))
237 /* Don't resume fork children that GDB does not know about yet. */
238 if ((vstop_event
->status
.kind () == TARGET_WAITKIND_FORKED
239 || vstop_event
->status
.kind () == TARGET_WAITKIND_VFORKED
)
240 && vstop_event
->status
.child_ptid ().matches (filter_ptid
))
249 in_queued_stop_replies (ptid_t ptid
)
251 for (notif_event
*event
: notif_stop
.queue
)
253 if (in_queued_stop_replies_ptid (event
, ptid
))
260 struct notif_server notif_stop
=
262 "vStopped", "Stop", {}, vstop_notif_reply
,
266 target_running (void)
268 return get_first_thread () != NULL
;
271 /* See gdbsupport/common-inferior.h. */
276 return !wrapper_argv
.empty () ? wrapper_argv
.c_str () : NULL
;
279 /* See gdbsupport/common-inferior.h. */
282 get_exec_file (int err
)
284 if (err
&& program_path
.get () == NULL
)
285 error (_("No executable file specified."));
287 return program_path
.get ();
299 attach_inferior (int pid
)
301 client_state
&cs
= get_client_state ();
302 /* myattach should return -1 if attaching is unsupported,
303 0 if it succeeded, and call error() otherwise. */
305 if (find_process_pid (pid
) != nullptr)
306 error ("Already attached to process %d\n", pid
);
308 if (myattach (pid
) != 0)
311 fprintf (stderr
, "Attached; pid = %d\n", pid
);
314 /* FIXME - It may be that we should get the SIGNAL_PID from the
315 attach function, so that it can be the main thread instead of
316 whichever we were told to attach to. */
321 cs
.last_ptid
= mywait (ptid_t (pid
), &cs
.last_status
, 0, 0);
323 /* GDB knows to ignore the first SIGSTOP after attaching to a running
324 process using the "attach" command, but this is different; it's
325 just using "target remote". Pretend it's just starting up. */
326 if (cs
.last_status
.kind () == TARGET_WAITKIND_STOPPED
327 && cs
.last_status
.sig () == GDB_SIGNAL_STOP
)
328 cs
.last_status
.set_stopped (GDB_SIGNAL_TRAP
);
330 current_thread
->last_resume_kind
= resume_stop
;
331 current_thread
->last_status
= cs
.last_status
;
337 /* Decode a qXfer read request. Return 0 if everything looks OK,
341 decode_xfer_read (char *buf
, CORE_ADDR
*ofs
, unsigned int *len
)
343 /* After the read marker and annex, qXfer looks like a
344 traditional 'm' packet. */
345 decode_m_packet (buf
, ofs
, len
);
351 decode_xfer (char *buf
, char **object
, char **rw
, char **annex
, char **offset
)
353 /* Extract and NUL-terminate the object. */
355 while (*buf
&& *buf
!= ':')
361 /* Extract and NUL-terminate the read/write action. */
363 while (*buf
&& *buf
!= ':')
369 /* Extract and NUL-terminate the annex. */
371 while (*buf
&& *buf
!= ':')
381 /* Write the response to a successful qXfer read. Returns the
382 length of the (binary) data stored in BUF, corresponding
383 to as much of DATA/LEN as we could fit. IS_MORE controls
384 the first character of the response. */
386 write_qxfer_response (char *buf
, const gdb_byte
*data
, int len
, int is_more
)
395 return remote_escape_output (data
, len
, 1, (unsigned char *) buf
+ 1,
396 &out_len
, PBUFSIZ
- 2) + 1;
399 /* Handle btrace enabling in BTS format. */
402 handle_btrace_enable_bts (struct thread_info
*thread
)
404 if (thread
->btrace
!= NULL
)
405 error (_("Btrace already enabled."));
407 current_btrace_conf
.format
= BTRACE_FORMAT_BTS
;
408 thread
->btrace
= target_enable_btrace (thread
, ¤t_btrace_conf
);
411 /* Handle btrace enabling in Intel Processor Trace format. */
414 handle_btrace_enable_pt (struct thread_info
*thread
)
416 if (thread
->btrace
!= NULL
)
417 error (_("Btrace already enabled."));
419 current_btrace_conf
.format
= BTRACE_FORMAT_PT
;
420 thread
->btrace
= target_enable_btrace (thread
, ¤t_btrace_conf
);
423 /* Handle btrace disabling. */
426 handle_btrace_disable (struct thread_info
*thread
)
429 if (thread
->btrace
== NULL
)
430 error (_("Branch tracing not enabled."));
432 if (target_disable_btrace (thread
->btrace
) != 0)
433 error (_("Could not disable branch tracing."));
435 thread
->btrace
= NULL
;
438 /* Handle the "Qbtrace" packet. */
441 handle_btrace_general_set (char *own_buf
)
443 client_state
&cs
= get_client_state ();
444 struct thread_info
*thread
;
447 if (!startswith (own_buf
, "Qbtrace:"))
450 op
= own_buf
+ strlen ("Qbtrace:");
452 if (cs
.general_thread
== null_ptid
453 || cs
.general_thread
== minus_one_ptid
)
455 strcpy (own_buf
, "E.Must select a single thread.");
459 thread
= find_thread_ptid (cs
.general_thread
);
462 strcpy (own_buf
, "E.No such thread.");
468 if (strcmp (op
, "bts") == 0)
469 handle_btrace_enable_bts (thread
);
470 else if (strcmp (op
, "pt") == 0)
471 handle_btrace_enable_pt (thread
);
472 else if (strcmp (op
, "off") == 0)
473 handle_btrace_disable (thread
);
475 error (_("Bad Qbtrace operation. Use bts, pt, or off."));
479 catch (const gdb_exception_error
&exception
)
481 sprintf (own_buf
, "E.%s", exception
.what ());
487 /* Handle the "Qbtrace-conf" packet. */
490 handle_btrace_conf_general_set (char *own_buf
)
492 client_state
&cs
= get_client_state ();
493 struct thread_info
*thread
;
496 if (!startswith (own_buf
, "Qbtrace-conf:"))
499 op
= own_buf
+ strlen ("Qbtrace-conf:");
501 if (cs
.general_thread
== null_ptid
502 || cs
.general_thread
== minus_one_ptid
)
504 strcpy (own_buf
, "E.Must select a single thread.");
508 thread
= find_thread_ptid (cs
.general_thread
);
511 strcpy (own_buf
, "E.No such thread.");
515 if (startswith (op
, "bts:size="))
521 size
= strtoul (op
+ strlen ("bts:size="), &endp
, 16);
522 if (endp
== NULL
|| *endp
!= 0 || errno
!= 0 || size
> UINT_MAX
)
524 strcpy (own_buf
, "E.Bad size value.");
528 current_btrace_conf
.bts
.size
= (unsigned int) size
;
530 else if (strncmp (op
, "pt:size=", strlen ("pt:size=")) == 0)
536 size
= strtoul (op
+ strlen ("pt:size="), &endp
, 16);
537 if (endp
== NULL
|| *endp
!= 0 || errno
!= 0 || size
> UINT_MAX
)
539 strcpy (own_buf
, "E.Bad size value.");
543 current_btrace_conf
.pt
.size
= (unsigned int) size
;
547 strcpy (own_buf
, "E.Bad Qbtrace configuration option.");
555 /* Create the qMemTags packet reply given TAGS.
557 Returns true if parsing succeeded and false otherwise. */
560 create_fetch_memtags_reply (char *reply
, const gdb::byte_vector
&tags
)
562 /* It is an error to pass a zero-sized tag vector. */
563 gdb_assert (tags
.size () != 0);
565 std::string
packet ("m");
567 /* Write the tag data. */
568 packet
+= bin2hex (tags
.data (), tags
.size ());
570 /* Check if the reply is too big for the packet to handle. */
571 if (PBUFSIZ
< packet
.size ())
574 strcpy (reply
, packet
.c_str ());
578 /* Parse the QMemTags request into ADDR, LEN and TAGS.
580 Returns true if parsing succeeded and false otherwise. */
583 parse_store_memtags_request (char *request
, CORE_ADDR
*addr
, size_t *len
,
584 gdb::byte_vector
&tags
, int *type
)
586 gdb_assert (startswith (request
, "QMemTags:"));
588 const char *p
= request
+ strlen ("QMemTags:");
590 /* Read address and length. */
591 unsigned int length
= 0;
592 p
= decode_m_packet_params (p
, addr
, &length
, ':');
595 /* Read the tag type. */
596 ULONGEST tag_type
= 0;
597 p
= unpack_varlen_hex (p
, &tag_type
);
598 *type
= (int) tag_type
;
600 /* Make sure there is a colon after the type. */
604 /* Skip the colon. */
607 /* Read the tag data. */
613 /* Handle all of the extended 'Q' packets. */
616 handle_general_set (char *own_buf
)
618 client_state
&cs
= get_client_state ();
619 if (startswith (own_buf
, "QPassSignals:"))
621 int numsigs
= (int) GDB_SIGNAL_LAST
, i
;
622 const char *p
= own_buf
+ strlen ("QPassSignals:");
625 p
= decode_address_to_semicolon (&cursig
, p
);
626 for (i
= 0; i
< numsigs
; i
++)
630 cs
.pass_signals
[i
] = 1;
632 /* Keep looping, to clear the remaining signals. */
635 p
= decode_address_to_semicolon (&cursig
, p
);
638 cs
.pass_signals
[i
] = 0;
640 strcpy (own_buf
, "OK");
644 if (startswith (own_buf
, "QProgramSignals:"))
646 int numsigs
= (int) GDB_SIGNAL_LAST
, i
;
647 const char *p
= own_buf
+ strlen ("QProgramSignals:");
650 cs
.program_signals_p
= 1;
652 p
= decode_address_to_semicolon (&cursig
, p
);
653 for (i
= 0; i
< numsigs
; i
++)
657 cs
.program_signals
[i
] = 1;
659 /* Keep looping, to clear the remaining signals. */
662 p
= decode_address_to_semicolon (&cursig
, p
);
665 cs
.program_signals
[i
] = 0;
667 strcpy (own_buf
, "OK");
671 if (startswith (own_buf
, "QCatchSyscalls:"))
673 const char *p
= own_buf
+ sizeof ("QCatchSyscalls:") - 1;
676 struct process_info
*process
;
678 if (!target_running () || !target_supports_catch_syscall ())
684 if (strcmp (p
, "0") == 0)
686 else if (p
[0] == '1' && (p
[1] == ';' || p
[1] == '\0'))
690 fprintf (stderr
, "Unknown catch-syscalls mode requested: %s\n",
696 process
= current_process ();
697 process
->syscalls_to_catch
.clear ();
707 p
= decode_address_to_semicolon (&sysno
, p
);
708 process
->syscalls_to_catch
.push_back (sysno
);
712 process
->syscalls_to_catch
.push_back (ANY_SYSCALL
);
719 if (strcmp (own_buf
, "QEnvironmentReset") == 0)
721 our_environ
= gdb_environ::from_host_environ ();
727 if (startswith (own_buf
, "QEnvironmentHexEncoded:"))
729 const char *p
= own_buf
+ sizeof ("QEnvironmentHexEncoded:") - 1;
730 /* The final form of the environment variable. FINAL_VAR will
731 hold the 'VAR=VALUE' format. */
732 std::string final_var
= hex2str (p
);
733 std::string var_name
, var_value
;
735 remote_debug_printf ("[QEnvironmentHexEncoded received '%s']", p
);
736 remote_debug_printf ("[Environment variable to be set: '%s']",
739 size_t pos
= final_var
.find ('=');
740 if (pos
== std::string::npos
)
742 warning (_("Unexpected format for environment variable: '%s'"),
748 var_name
= final_var
.substr (0, pos
);
749 var_value
= final_var
.substr (pos
+ 1, std::string::npos
);
751 our_environ
.set (var_name
.c_str (), var_value
.c_str ());
757 if (startswith (own_buf
, "QEnvironmentUnset:"))
759 const char *p
= own_buf
+ sizeof ("QEnvironmentUnset:") - 1;
760 std::string varname
= hex2str (p
);
762 remote_debug_printf ("[QEnvironmentUnset received '%s']", p
);
763 remote_debug_printf ("[Environment variable to be unset: '%s']",
766 our_environ
.unset (varname
.c_str ());
772 if (strcmp (own_buf
, "QStartNoAckMode") == 0)
774 remote_debug_printf ("[noack mode enabled]");
781 if (startswith (own_buf
, "QNonStop:"))
783 char *mode
= own_buf
+ 9;
787 if (strcmp (mode
, "0") == 0)
789 else if (strcmp (mode
, "1") == 0)
793 /* We don't know what this mode is, so complain to
795 fprintf (stderr
, "Unknown non-stop mode requested: %s\n",
801 req_str
= req
? "non-stop" : "all-stop";
802 if (the_target
->start_non_stop (req
== 1) != 0)
804 fprintf (stderr
, "Setting %s mode failed\n", req_str
);
809 non_stop
= (req
!= 0);
811 remote_debug_printf ("[%s mode enabled]", req_str
);
817 if (startswith (own_buf
, "QDisableRandomization:"))
819 char *packet
= own_buf
+ strlen ("QDisableRandomization:");
822 unpack_varlen_hex (packet
, &setting
);
823 cs
.disable_randomization
= setting
;
825 remote_debug_printf (cs
.disable_randomization
826 ? "[address space randomization disabled]"
827 : "[address space randomization enabled]");
833 if (target_supports_tracepoints ()
834 && handle_tracepoint_general_set (own_buf
))
837 if (startswith (own_buf
, "QAgent:"))
839 char *mode
= own_buf
+ strlen ("QAgent:");
842 if (strcmp (mode
, "0") == 0)
844 else if (strcmp (mode
, "1") == 0)
848 /* We don't know what this value is, so complain to GDB. */
849 sprintf (own_buf
, "E.Unknown QAgent value");
853 /* Update the flag. */
855 remote_debug_printf ("[%s agent]", req
? "Enable" : "Disable");
860 if (handle_btrace_general_set (own_buf
))
863 if (handle_btrace_conf_general_set (own_buf
))
866 if (startswith (own_buf
, "QThreadEvents:"))
868 char *mode
= own_buf
+ strlen ("QThreadEvents:");
869 enum tribool req
= TRIBOOL_UNKNOWN
;
871 if (strcmp (mode
, "0") == 0)
873 else if (strcmp (mode
, "1") == 0)
877 /* We don't know what this mode is, so complain to GDB. */
879 = string_printf ("E.Unknown thread-events mode requested: %s\n",
881 strcpy (own_buf
, err
.c_str ());
885 cs
.report_thread_events
= (req
== TRIBOOL_TRUE
);
887 remote_debug_printf ("[thread events are now %s]\n",
888 cs
.report_thread_events
? "enabled" : "disabled");
894 if (startswith (own_buf
, "QStartupWithShell:"))
896 const char *value
= own_buf
+ strlen ("QStartupWithShell:");
898 if (strcmp (value
, "1") == 0)
899 startup_with_shell
= true;
900 else if (strcmp (value
, "0") == 0)
901 startup_with_shell
= false;
905 fprintf (stderr
, "Unknown value to startup-with-shell: %s\n",
911 remote_debug_printf ("[Inferior will %s started with shell]",
912 startup_with_shell
? "be" : "not be");
918 if (startswith (own_buf
, "QSetWorkingDir:"))
920 const char *p
= own_buf
+ strlen ("QSetWorkingDir:");
924 std::string path
= hex2str (p
);
926 remote_debug_printf ("[Set the inferior's current directory to %s]",
929 set_inferior_cwd (std::move (path
));
933 /* An empty argument means that we should clear out any
934 previously set cwd for the inferior. */
935 set_inferior_cwd ("");
937 remote_debug_printf ("[Unset the inferior's current directory; will "
938 "use gdbserver's cwd]");
946 /* Handle store memory tags packets. */
947 if (startswith (own_buf
, "QMemTags:")
948 && target_supports_memory_tagging ())
950 gdb::byte_vector tags
;
955 require_running_or_return (own_buf
);
957 bool ret
= parse_store_memtags_request (own_buf
, &addr
, &len
, tags
,
961 ret
= the_target
->store_memtags (addr
, len
, tags
, type
);
971 /* Otherwise we didn't know what packet it was. Say we didn't
977 get_features_xml (const char *annex
)
979 const struct target_desc
*desc
= current_target_desc ();
981 /* `desc->xmltarget' defines what to return when looking for the
982 "target.xml" file. Its contents can either be verbatim XML code
983 (prefixed with a '@') or else the name of the actual XML file to
984 be used in place of "target.xml".
986 This variable is set up from the auto-generated
987 init_registers_... routine for the current target. */
989 if (strcmp (annex
, "target.xml") == 0)
991 const char *ret
= tdesc_get_features_xml (desc
);
1003 /* Look for the annex. */
1004 for (i
= 0; xml_builtin
[i
][0] != NULL
; i
++)
1005 if (strcmp (annex
, xml_builtin
[i
][0]) == 0)
1008 if (xml_builtin
[i
][0] != NULL
)
1009 return xml_builtin
[i
][1];
1017 monitor_show_help (void)
1019 monitor_output ("The following monitor commands are supported:\n");
1020 monitor_output (" set debug <0|1>\n");
1021 monitor_output (" Enable general debugging messages\n");
1022 monitor_output (" set debug-hw-points <0|1>\n");
1023 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
1024 monitor_output (" set remote-debug <0|1>\n");
1025 monitor_output (" Enable remote protocol debugging messages\n");
1026 monitor_output (" set event-loop-debug <0|1>\n");
1027 monitor_output (" Enable event loop debugging messages\n");
1028 monitor_output (" set debug-format option1[,option2,...]\n");
1029 monitor_output (" Add additional information to debugging messages\n");
1030 monitor_output (" Options: all, none");
1031 monitor_output (", timestamp");
1032 monitor_output ("\n");
1033 monitor_output (" exit\n");
1034 monitor_output (" Quit GDBserver\n");
1037 /* Read trace frame or inferior memory. Returns the number of bytes
1038 actually read, zero when no further transfer is possible, and -1 on
1039 error. Return of a positive value smaller than LEN does not
1040 indicate there's no more to be read, only the end of the transfer.
1041 E.g., when GDB reads memory from a traceframe, a first request may
1042 be served from a memory block that does not cover the whole request
1043 length. A following request gets the rest served from either
1044 another block (of the same traceframe) or from the read-only
1048 gdb_read_memory (CORE_ADDR memaddr
, unsigned char *myaddr
, int len
)
1050 client_state
&cs
= get_client_state ();
1053 if (cs
.current_traceframe
>= 0)
1056 ULONGEST length
= len
;
1058 if (traceframe_read_mem (cs
.current_traceframe
,
1059 memaddr
, myaddr
, len
, &nbytes
))
1061 /* Data read from trace buffer, we're done. */
1064 if (!in_readonly_region (memaddr
, length
))
1066 /* Otherwise we have a valid readonly case, fall through. */
1067 /* (assume no half-trace half-real blocks for now) */
1070 if (set_desired_process ())
1071 res
= read_inferior_memory (memaddr
, myaddr
, len
);
1075 return res
== 0 ? len
: -1;
1078 /* Write trace frame or inferior memory. Actually, writing to trace
1079 frames is forbidden. */
1082 gdb_write_memory (CORE_ADDR memaddr
, const unsigned char *myaddr
, int len
)
1084 client_state
&cs
= get_client_state ();
1085 if (cs
.current_traceframe
>= 0)
1091 if (set_desired_process ())
1092 ret
= target_write_memory (memaddr
, myaddr
, len
);
1099 /* Handle qSearch:memory packets. */
1102 handle_search_memory (char *own_buf
, int packet_len
)
1104 CORE_ADDR start_addr
;
1105 CORE_ADDR search_space_len
;
1107 unsigned int pattern_len
;
1109 CORE_ADDR found_addr
;
1110 int cmd_name_len
= sizeof ("qSearch:memory:") - 1;
1112 pattern
= (gdb_byte
*) malloc (packet_len
);
1113 if (pattern
== NULL
)
1114 error ("Unable to allocate memory to perform the search");
1116 if (decode_search_memory_packet (own_buf
+ cmd_name_len
,
1117 packet_len
- cmd_name_len
,
1118 &start_addr
, &search_space_len
,
1119 pattern
, &pattern_len
) < 0)
1122 error ("Error in parsing qSearch:memory packet");
1125 auto read_memory
= [] (CORE_ADDR addr
, gdb_byte
*result
, size_t len
)
1127 return gdb_read_memory (addr
, result
, len
) == len
;
1130 found
= simple_search_memory (read_memory
, start_addr
, search_space_len
,
1131 pattern
, pattern_len
, &found_addr
);
1134 sprintf (own_buf
, "1,%lx", (long) found_addr
);
1135 else if (found
== 0)
1136 strcpy (own_buf
, "0");
1138 strcpy (own_buf
, "E00");
1143 /* Handle the "D" packet. */
1146 handle_detach (char *own_buf
)
1148 client_state
&cs
= get_client_state ();
1150 process_info
*process
;
1152 if (cs
.multi_process
)
1155 int pid
= strtol (&own_buf
[2], NULL
, 16);
1157 process
= find_process_pid (pid
);
1161 process
= (current_thread
!= nullptr
1162 ? get_thread_process (current_thread
)
1166 if (process
== NULL
)
1168 write_enn (own_buf
);
1172 if ((tracing
&& disconnected_tracing
) || any_persistent_commands (process
))
1174 if (tracing
&& disconnected_tracing
)
1176 "Disconnected tracing in effect, "
1177 "leaving gdbserver attached to the process\n");
1179 if (any_persistent_commands (process
))
1181 "Persistent commands are present, "
1182 "leaving gdbserver attached to the process\n");
1184 /* Make sure we're in non-stop/async mode, so we we can both
1185 wait for an async socket accept, and handle async target
1186 events simultaneously. There's also no point either in
1187 having the target stop all threads, when we're going to
1188 pass signals down without informing GDB. */
1191 threads_debug_printf ("Forcing non-stop mode");
1194 the_target
->start_non_stop (true);
1197 process
->gdb_detached
= 1;
1199 /* Detaching implicitly resumes all threads. */
1200 target_continue_no_signal (minus_one_ptid
);
1206 fprintf (stderr
, "Detaching from process %d\n", process
->pid
);
1209 /* We'll need this after PROCESS has been destroyed. */
1210 int pid
= process
->pid
;
1212 /* If this process has an unreported fork child, that child is not known to
1213 GDB, so GDB won't take care of detaching it. We must do it here.
1215 Here, we specifically don't want to use "safe iteration", as detaching
1216 another process might delete the next thread in the iteration, which is
1217 the one saved by the safe iterator. We will never delete the currently
1218 iterated on thread, so standard iteration should be safe. */
1219 for (thread_info
*thread
: all_threads
)
1221 /* Only threads that are of the process we are detaching. */
1222 if (thread
->id
.pid () != pid
)
1225 /* Only threads that have a pending fork event. */
1226 thread_info
*child
= target_thread_pending_child (thread
);
1227 if (child
== nullptr)
1230 process_info
*fork_child_process
= get_thread_process (child
);
1231 gdb_assert (fork_child_process
!= nullptr);
1233 int fork_child_pid
= fork_child_process
->pid
;
1235 if (detach_inferior (fork_child_process
) != 0)
1236 warning (_("Failed to detach fork child %s, child of %s"),
1237 target_pid_to_str (ptid_t (fork_child_pid
)).c_str (),
1238 target_pid_to_str (thread
->id
).c_str ());
1241 if (detach_inferior (process
) != 0)
1242 write_enn (own_buf
);
1245 discard_queued_stop_replies (ptid_t (pid
));
1248 if (extended_protocol
|| target_running ())
1250 /* There is still at least one inferior remaining or
1251 we are in extended mode, so don't terminate gdbserver,
1252 and instead treat this like a normal program exit. */
1253 cs
.last_status
.set_exited (0);
1254 cs
.last_ptid
= ptid_t (pid
);
1256 switch_to_thread (nullptr);
1263 /* If we are attached, then we can exit. Otherwise, we
1264 need to hang around doing nothing, until the child is
1266 join_inferior (pid
);
1272 /* Parse options to --debug-format= and "monitor set debug-format".
1273 ARG is the text after "--debug-format=" or "monitor set debug-format".
1274 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1275 This triggers calls to monitor_output.
1276 The result is an empty string if all options were parsed ok, otherwise an
1277 error message which the caller must free.
1279 N.B. These commands affect all debug format settings, they are not
1280 cumulative. If a format is not specified, it is turned off.
1281 However, we don't go to extra trouble with things like
1282 "monitor set debug-format all,none,timestamp".
1283 Instead we just parse them one at a time, in order.
1285 The syntax for "monitor set debug" we support here is not identical
1286 to gdb's "set debug foo on|off" because we also use this function to
1287 parse "--debug-format=foo,bar". */
1290 parse_debug_format_options (const char *arg
, int is_monitor
)
1292 /* First turn all debug format options off. */
1293 debug_timestamp
= 0;
1295 /* First remove leading spaces, for "monitor set debug-format". */
1296 while (isspace (*arg
))
1299 std::vector
<gdb::unique_xmalloc_ptr
<char>> options
1300 = delim_string_to_char_ptr_vec (arg
, ',');
1302 for (const gdb::unique_xmalloc_ptr
<char> &option
: options
)
1304 if (strcmp (option
.get (), "all") == 0)
1306 debug_timestamp
= 1;
1308 monitor_output ("All extra debug format options enabled.\n");
1310 else if (strcmp (option
.get (), "none") == 0)
1312 debug_timestamp
= 0;
1314 monitor_output ("All extra debug format options disabled.\n");
1316 else if (strcmp (option
.get (), "timestamp") == 0)
1318 debug_timestamp
= 1;
1320 monitor_output ("Timestamps will be added to debug output.\n");
1322 else if (*option
== '\0')
1324 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1328 return string_printf ("Unknown debug-format argument: \"%s\"\n",
1332 return std::string ();
1335 /* Handle monitor commands not handled by target-specific handlers. */
1338 handle_monitor_command (char *mon
, char *own_buf
)
1340 if (strcmp (mon
, "set debug 1") == 0)
1342 debug_threads
= true;
1343 monitor_output ("Debug output enabled.\n");
1345 else if (strcmp (mon
, "set debug 0") == 0)
1347 debug_threads
= false;
1348 monitor_output ("Debug output disabled.\n");
1350 else if (strcmp (mon
, "set debug-hw-points 1") == 0)
1352 show_debug_regs
= 1;
1353 monitor_output ("H/W point debugging output enabled.\n");
1355 else if (strcmp (mon
, "set debug-hw-points 0") == 0)
1357 show_debug_regs
= 0;
1358 monitor_output ("H/W point debugging output disabled.\n");
1360 else if (strcmp (mon
, "set remote-debug 1") == 0)
1362 remote_debug
= true;
1363 monitor_output ("Protocol debug output enabled.\n");
1365 else if (strcmp (mon
, "set remote-debug 0") == 0)
1367 remote_debug
= false;
1368 monitor_output ("Protocol debug output disabled.\n");
1370 else if (strcmp (mon
, "set event-loop-debug 1") == 0)
1372 debug_event_loop
= debug_event_loop_kind::ALL
;
1373 monitor_output ("Event loop debug output enabled.\n");
1375 else if (strcmp (mon
, "set event-loop-debug 0") == 0)
1377 debug_event_loop
= debug_event_loop_kind::OFF
;
1378 monitor_output ("Event loop debug output disabled.\n");
1380 else if (startswith (mon
, "set debug-format "))
1382 std::string error_msg
1383 = parse_debug_format_options (mon
+ sizeof ("set debug-format ") - 1,
1386 if (!error_msg
.empty ())
1388 monitor_output (error_msg
.c_str ());
1389 monitor_show_help ();
1390 write_enn (own_buf
);
1393 else if (strcmp (mon
, "set debug-file") == 0)
1394 debug_set_output (nullptr);
1395 else if (startswith (mon
, "set debug-file "))
1396 debug_set_output (mon
+ sizeof ("set debug-file ") - 1);
1397 else if (strcmp (mon
, "help") == 0)
1398 monitor_show_help ();
1399 else if (strcmp (mon
, "exit") == 0)
1400 exit_requested
= true;
1403 monitor_output ("Unknown monitor command.\n\n");
1404 monitor_show_help ();
1405 write_enn (own_buf
);
1409 /* Associates a callback with each supported qXfer'able object. */
1413 /* The object this handler handles. */
1416 /* Request that the target transfer up to LEN 8-bit bytes of the
1417 target's OBJECT. The OFFSET, for a seekable object, specifies
1418 the starting point. The ANNEX can be used to provide additional
1419 data-specific information to the target.
1421 Return the number of bytes actually transfered, zero when no
1422 further transfer is possible, -1 on error, -2 when the transfer
1423 is not supported, and -3 on a verbose error message that should
1424 be preserved. Return of a positive value smaller than LEN does
1425 not indicate the end of the object, only the end of the transfer.
1427 One, and only one, of readbuf or writebuf must be non-NULL. */
1428 int (*xfer
) (const char *annex
,
1429 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1430 ULONGEST offset
, LONGEST len
);
1433 /* Handle qXfer:auxv:read. */
1436 handle_qxfer_auxv (const char *annex
,
1437 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1438 ULONGEST offset
, LONGEST len
)
1440 if (!the_target
->supports_read_auxv () || writebuf
!= NULL
)
1443 if (annex
[0] != '\0' || current_thread
== NULL
)
1446 return the_target
->read_auxv (offset
, readbuf
, len
);
1449 /* Handle qXfer:exec-file:read. */
1452 handle_qxfer_exec_file (const char *annex
,
1453 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1454 ULONGEST offset
, LONGEST len
)
1459 if (!the_target
->supports_pid_to_exec_file () || writebuf
!= NULL
)
1462 if (annex
[0] == '\0')
1464 if (current_thread
== NULL
)
1467 pid
= pid_of (current_thread
);
1471 annex
= unpack_varlen_hex (annex
, &pid
);
1472 if (annex
[0] != '\0')
1479 const char *file
= the_target
->pid_to_exec_file (pid
);
1483 total_len
= strlen (file
);
1485 if (offset
> total_len
)
1488 if (offset
+ len
> total_len
)
1489 len
= total_len
- offset
;
1491 memcpy (readbuf
, file
+ offset
, len
);
1495 /* Handle qXfer:features:read. */
1498 handle_qxfer_features (const char *annex
,
1499 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1500 ULONGEST offset
, LONGEST len
)
1502 const char *document
;
1505 if (writebuf
!= NULL
)
1508 if (!target_running ())
1511 /* Grab the correct annex. */
1512 document
= get_features_xml (annex
);
1513 if (document
== NULL
)
1516 total_len
= strlen (document
);
1518 if (offset
> total_len
)
1521 if (offset
+ len
> total_len
)
1522 len
= total_len
- offset
;
1524 memcpy (readbuf
, document
+ offset
, len
);
1528 /* Handle qXfer:libraries:read. */
1531 handle_qxfer_libraries (const char *annex
,
1532 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1533 ULONGEST offset
, LONGEST len
)
1535 if (writebuf
!= NULL
)
1538 if (annex
[0] != '\0' || current_thread
== NULL
)
1541 std::string document
= "<library-list version=\"1.0\">\n";
1543 process_info
*proc
= current_process ();
1544 for (const dll_info
&dll
: proc
->all_dlls
)
1545 document
+= string_printf
1546 (" <library name=\"%s\"><segment address=\"0x%s\"/></library>\n",
1547 dll
.name
.c_str (), paddress (dll
.base_addr
));
1549 document
+= "</library-list>\n";
1551 if (offset
> document
.length ())
1554 if (offset
+ len
> document
.length ())
1555 len
= document
.length () - offset
;
1557 memcpy (readbuf
, &document
[offset
], len
);
1562 /* Handle qXfer:libraries-svr4:read. */
1565 handle_qxfer_libraries_svr4 (const char *annex
,
1566 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1567 ULONGEST offset
, LONGEST len
)
1569 if (writebuf
!= NULL
)
1572 if (current_thread
== NULL
1573 || !the_target
->supports_qxfer_libraries_svr4 ())
1576 return the_target
->qxfer_libraries_svr4 (annex
, readbuf
, writebuf
,
1580 /* Handle qXfer:osadata:read. */
1583 handle_qxfer_osdata (const char *annex
,
1584 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1585 ULONGEST offset
, LONGEST len
)
1587 if (!the_target
->supports_qxfer_osdata () || writebuf
!= NULL
)
1590 return the_target
->qxfer_osdata (annex
, readbuf
, NULL
, offset
, len
);
1593 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1596 handle_qxfer_siginfo (const char *annex
,
1597 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1598 ULONGEST offset
, LONGEST len
)
1600 if (!the_target
->supports_qxfer_siginfo ())
1603 if (annex
[0] != '\0' || current_thread
== NULL
)
1606 return the_target
->qxfer_siginfo (annex
, readbuf
, writebuf
, offset
, len
);
1609 /* Handle qXfer:statictrace:read. */
1612 handle_qxfer_statictrace (const char *annex
,
1613 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1614 ULONGEST offset
, LONGEST len
)
1616 client_state
&cs
= get_client_state ();
1619 if (writebuf
!= NULL
)
1622 if (annex
[0] != '\0' || current_thread
== NULL
1623 || cs
.current_traceframe
== -1)
1626 if (traceframe_read_sdata (cs
.current_traceframe
, offset
,
1627 readbuf
, len
, &nbytes
))
1632 /* Helper for handle_qxfer_threads_proper.
1633 Emit the XML to describe the thread of INF. */
1636 handle_qxfer_threads_worker (thread_info
*thread
, struct buffer
*buffer
)
1638 ptid_t ptid
= ptid_of (thread
);
1640 int core
= target_core_of_thread (ptid
);
1642 const char *name
= target_thread_name (ptid
);
1645 bool handle_status
= target_thread_handle (ptid
, &handle
, &handle_len
);
1647 /* If this is a fork or vfork child (has a fork parent), GDB does not yet
1648 know about this process, and must not know about it until it gets the
1649 corresponding (v)fork event. Exclude this thread from the list. */
1650 if (target_thread_pending_parent (thread
) != nullptr)
1653 write_ptid (ptid_s
, ptid
);
1655 buffer_xml_printf (buffer
, "<thread id=\"%s\"", ptid_s
);
1659 sprintf (core_s
, "%d", core
);
1660 buffer_xml_printf (buffer
, " core=\"%s\"", core_s
);
1664 buffer_xml_printf (buffer
, " name=\"%s\"", name
);
1668 char *handle_s
= (char *) alloca (handle_len
* 2 + 1);
1669 bin2hex (handle
, handle_s
, handle_len
);
1670 buffer_xml_printf (buffer
, " handle=\"%s\"", handle_s
);
1673 buffer_xml_printf (buffer
, "/>\n");
1676 /* Helper for handle_qxfer_threads. Return true on success, false
1680 handle_qxfer_threads_proper (struct buffer
*buffer
)
1682 buffer_grow_str (buffer
, "<threads>\n");
1684 /* The target may need to access memory and registers (e.g. via
1685 libthread_db) to fetch thread properties. Even if don't need to
1686 stop threads to access memory, we still will need to be able to
1687 access registers, and other ptrace accesses like
1688 PTRACE_GET_THREAD_AREA that require a paused thread. Pause all
1689 threads here, so that we pause each thread at most once for all
1692 target_pause_all (true);
1694 for_each_thread ([&] (thread_info
*thread
)
1696 handle_qxfer_threads_worker (thread
, buffer
);
1700 target_unpause_all (true);
1702 buffer_grow_str0 (buffer
, "</threads>\n");
1706 /* Handle qXfer:threads:read. */
1709 handle_qxfer_threads (const char *annex
,
1710 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1711 ULONGEST offset
, LONGEST len
)
1713 static char *result
= 0;
1714 static unsigned int result_length
= 0;
1716 if (writebuf
!= NULL
)
1719 if (annex
[0] != '\0')
1724 struct buffer buffer
;
1725 /* When asked for data at offset 0, generate everything and store into
1726 'result'. Successive reads will be served off 'result'. */
1730 buffer_init (&buffer
);
1732 bool res
= handle_qxfer_threads_proper (&buffer
);
1734 result
= buffer_finish (&buffer
);
1735 result_length
= strlen (result
);
1736 buffer_free (&buffer
);
1742 if (offset
>= result_length
)
1744 /* We're out of data. */
1751 if (len
> result_length
- offset
)
1752 len
= result_length
- offset
;
1754 memcpy (readbuf
, result
+ offset
, len
);
1759 /* Handle qXfer:traceframe-info:read. */
1762 handle_qxfer_traceframe_info (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 char *result
= 0;
1768 static unsigned int result_length
= 0;
1770 if (writebuf
!= NULL
)
1773 if (!target_running () || annex
[0] != '\0' || cs
.current_traceframe
== -1)
1778 struct buffer buffer
;
1780 /* When asked for data at offset 0, generate everything and
1781 store into 'result'. Successive reads will be served off
1785 buffer_init (&buffer
);
1787 traceframe_read_info (cs
.current_traceframe
, &buffer
);
1789 result
= buffer_finish (&buffer
);
1790 result_length
= strlen (result
);
1791 buffer_free (&buffer
);
1794 if (offset
>= result_length
)
1796 /* We're out of data. */
1803 if (len
> result_length
- offset
)
1804 len
= result_length
- offset
;
1806 memcpy (readbuf
, result
+ offset
, len
);
1810 /* Handle qXfer:fdpic:read. */
1813 handle_qxfer_fdpic (const char *annex
, gdb_byte
*readbuf
,
1814 const gdb_byte
*writebuf
, ULONGEST offset
, LONGEST len
)
1816 if (!the_target
->supports_read_loadmap ())
1819 if (current_thread
== NULL
)
1822 return the_target
->read_loadmap (annex
, offset
, readbuf
, len
);
1825 /* Handle qXfer:btrace:read. */
1828 handle_qxfer_btrace (const char *annex
,
1829 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1830 ULONGEST offset
, LONGEST len
)
1832 client_state
&cs
= get_client_state ();
1833 static struct buffer cache
;
1834 struct thread_info
*thread
;
1835 enum btrace_read_type type
;
1838 if (writebuf
!= NULL
)
1841 if (cs
.general_thread
== null_ptid
1842 || cs
.general_thread
== minus_one_ptid
)
1844 strcpy (cs
.own_buf
, "E.Must select a single thread.");
1848 thread
= find_thread_ptid (cs
.general_thread
);
1851 strcpy (cs
.own_buf
, "E.No such thread.");
1855 if (thread
->btrace
== NULL
)
1857 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
1861 if (strcmp (annex
, "all") == 0)
1862 type
= BTRACE_READ_ALL
;
1863 else if (strcmp (annex
, "new") == 0)
1864 type
= BTRACE_READ_NEW
;
1865 else if (strcmp (annex
, "delta") == 0)
1866 type
= BTRACE_READ_DELTA
;
1869 strcpy (cs
.own_buf
, "E.Bad annex.");
1875 buffer_free (&cache
);
1879 result
= target_read_btrace (thread
->btrace
, &cache
, type
);
1881 memcpy (cs
.own_buf
, cache
.buffer
, cache
.used_size
);
1883 catch (const gdb_exception_error
&exception
)
1885 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
1892 else if (offset
> cache
.used_size
)
1894 buffer_free (&cache
);
1898 if (len
> cache
.used_size
- offset
)
1899 len
= cache
.used_size
- offset
;
1901 memcpy (readbuf
, cache
.buffer
+ offset
, len
);
1906 /* Handle qXfer:btrace-conf:read. */
1909 handle_qxfer_btrace_conf (const char *annex
,
1910 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1911 ULONGEST offset
, LONGEST len
)
1913 client_state
&cs
= get_client_state ();
1914 static struct buffer cache
;
1915 struct thread_info
*thread
;
1918 if (writebuf
!= NULL
)
1921 if (annex
[0] != '\0')
1924 if (cs
.general_thread
== null_ptid
1925 || cs
.general_thread
== minus_one_ptid
)
1927 strcpy (cs
.own_buf
, "E.Must select a single thread.");
1931 thread
= find_thread_ptid (cs
.general_thread
);
1934 strcpy (cs
.own_buf
, "E.No such thread.");
1938 if (thread
->btrace
== NULL
)
1940 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
1946 buffer_free (&cache
);
1950 result
= target_read_btrace_conf (thread
->btrace
, &cache
);
1952 memcpy (cs
.own_buf
, cache
.buffer
, cache
.used_size
);
1954 catch (const gdb_exception_error
&exception
)
1956 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
1963 else if (offset
> cache
.used_size
)
1965 buffer_free (&cache
);
1969 if (len
> cache
.used_size
- offset
)
1970 len
= cache
.used_size
- offset
;
1972 memcpy (readbuf
, cache
.buffer
+ offset
, len
);
1977 static const struct qxfer qxfer_packets
[] =
1979 { "auxv", handle_qxfer_auxv
},
1980 { "btrace", handle_qxfer_btrace
},
1981 { "btrace-conf", handle_qxfer_btrace_conf
},
1982 { "exec-file", handle_qxfer_exec_file
},
1983 { "fdpic", handle_qxfer_fdpic
},
1984 { "features", handle_qxfer_features
},
1985 { "libraries", handle_qxfer_libraries
},
1986 { "libraries-svr4", handle_qxfer_libraries_svr4
},
1987 { "osdata", handle_qxfer_osdata
},
1988 { "siginfo", handle_qxfer_siginfo
},
1989 { "statictrace", handle_qxfer_statictrace
},
1990 { "threads", handle_qxfer_threads
},
1991 { "traceframe-info", handle_qxfer_traceframe_info
},
1995 handle_qxfer (char *own_buf
, int packet_len
, int *new_packet_len_p
)
2003 if (!startswith (own_buf
, "qXfer:"))
2006 /* Grab the object, r/w and annex. */
2007 if (decode_xfer (own_buf
+ 6, &object
, &rw
, &annex
, &offset
) < 0)
2009 write_enn (own_buf
);
2014 i
< sizeof (qxfer_packets
) / sizeof (qxfer_packets
[0]);
2017 const struct qxfer
*q
= &qxfer_packets
[i
];
2019 if (strcmp (object
, q
->object
) == 0)
2021 if (strcmp (rw
, "read") == 0)
2023 unsigned char *data
;
2028 /* Grab the offset and length. */
2029 if (decode_xfer_read (offset
, &ofs
, &len
) < 0)
2031 write_enn (own_buf
);
2035 /* Read one extra byte, as an indicator of whether there is
2037 if (len
> PBUFSIZ
- 2)
2039 data
= (unsigned char *) malloc (len
+ 1);
2042 write_enn (own_buf
);
2045 n
= (*q
->xfer
) (annex
, data
, NULL
, ofs
, len
+ 1);
2053 /* Preserve error message. */
2056 write_enn (own_buf
);
2058 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, len
, 1);
2060 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, n
, 0);
2065 else if (strcmp (rw
, "write") == 0)
2070 unsigned char *data
;
2072 strcpy (own_buf
, "E00");
2073 data
= (unsigned char *) malloc (packet_len
- (offset
- own_buf
));
2076 write_enn (own_buf
);
2079 if (decode_xfer_write (offset
, packet_len
- (offset
- own_buf
),
2080 &ofs
, &len
, data
) < 0)
2083 write_enn (own_buf
);
2087 n
= (*q
->xfer
) (annex
, NULL
, data
, ofs
, len
);
2095 /* Preserve error message. */
2098 write_enn (own_buf
);
2100 sprintf (own_buf
, "%x", n
);
2113 /* Compute 32 bit CRC from inferior memory.
2115 On success, return 32 bit CRC.
2116 On failure, return (unsigned long long) -1. */
2118 static unsigned long long
2119 crc32 (CORE_ADDR base
, int len
, unsigned int crc
)
2123 unsigned char byte
= 0;
2125 /* Return failure if memory read fails. */
2126 if (read_inferior_memory (base
, &byte
, 1) != 0)
2127 return (unsigned long long) -1;
2129 crc
= xcrc32 (&byte
, 1, crc
);
2132 return (unsigned long long) crc
;
2135 /* Parse the qMemTags packet request into ADDR and LEN. */
2138 parse_fetch_memtags_request (char *request
, CORE_ADDR
*addr
, size_t *len
,
2141 gdb_assert (startswith (request
, "qMemTags:"));
2143 const char *p
= request
+ strlen ("qMemTags:");
2145 /* Read address and length. */
2146 unsigned int length
= 0;
2147 p
= decode_m_packet_params (p
, addr
, &length
, ':');
2150 /* Read the tag type. */
2151 ULONGEST tag_type
= 0;
2152 p
= unpack_varlen_hex (p
, &tag_type
);
2153 *type
= (int) tag_type
;
2156 /* Add supported btrace packets to BUF. */
2159 supported_btrace_packets (char *buf
)
2161 strcat (buf
, ";Qbtrace:bts+");
2162 strcat (buf
, ";Qbtrace-conf:bts:size+");
2163 strcat (buf
, ";Qbtrace:pt+");
2164 strcat (buf
, ";Qbtrace-conf:pt:size+");
2165 strcat (buf
, ";Qbtrace:off+");
2166 strcat (buf
, ";qXfer:btrace:read+");
2167 strcat (buf
, ";qXfer:btrace-conf:read+");
2170 /* Handle all of the extended 'q' packets. */
2173 handle_query (char *own_buf
, int packet_len
, int *new_packet_len_p
)
2175 client_state
&cs
= get_client_state ();
2176 static std::list
<thread_info
*>::const_iterator thread_iter
;
2178 /* Reply the current thread id. */
2179 if (strcmp ("qC", own_buf
) == 0 && !disable_packet_qC
)
2182 require_running_or_return (own_buf
);
2184 if (cs
.general_thread
!= null_ptid
&& cs
.general_thread
!= minus_one_ptid
)
2185 ptid
= cs
.general_thread
;
2188 thread_iter
= all_threads
.begin ();
2189 ptid
= (*thread_iter
)->id
;
2192 sprintf (own_buf
, "QC");
2194 write_ptid (own_buf
, ptid
);
2198 if (strcmp ("qSymbol::", own_buf
) == 0)
2200 scoped_restore_current_thread restore_thread
;
2202 /* For qSymbol, GDB only changes the current thread if the
2203 previous current thread was of a different process. So if
2204 the previous thread is gone, we need to pick another one of
2205 the same process. This can happen e.g., if we followed an
2206 exec in a non-leader thread. */
2207 if (current_thread
== NULL
)
2209 thread_info
*any_thread
2210 = find_any_thread_of_pid (cs
.general_thread
.pid ());
2211 switch_to_thread (any_thread
);
2213 /* Just in case, if we didn't find a thread, then bail out
2214 instead of crashing. */
2215 if (current_thread
== NULL
)
2217 write_enn (own_buf
);
2222 /* GDB is suggesting new symbols have been loaded. This may
2223 mean a new shared library has been detected as loaded, so
2224 take the opportunity to check if breakpoints we think are
2225 inserted, still are. Note that it isn't guaranteed that
2226 we'll see this when a shared library is loaded, and nor will
2227 we see this for unloads (although breakpoints in unloaded
2228 libraries shouldn't trigger), as GDB may not find symbols for
2229 the library at all. We also re-validate breakpoints when we
2230 see a second GDB breakpoint for the same address, and or when
2231 we access breakpoint shadows. */
2232 validate_breakpoints ();
2234 if (target_supports_tracepoints ())
2235 tracepoint_look_up_symbols ();
2237 if (current_thread
!= NULL
)
2238 the_target
->look_up_symbols ();
2240 strcpy (own_buf
, "OK");
2244 if (!disable_packet_qfThreadInfo
)
2246 if (strcmp ("qfThreadInfo", own_buf
) == 0)
2248 require_running_or_return (own_buf
);
2249 thread_iter
= all_threads
.begin ();
2252 ptid_t ptid
= (*thread_iter
)->id
;
2253 write_ptid (own_buf
, ptid
);
2258 if (strcmp ("qsThreadInfo", own_buf
) == 0)
2260 require_running_or_return (own_buf
);
2261 if (thread_iter
!= all_threads
.end ())
2264 ptid_t ptid
= (*thread_iter
)->id
;
2265 write_ptid (own_buf
, ptid
);
2271 sprintf (own_buf
, "l");
2277 if (the_target
->supports_read_offsets ()
2278 && strcmp ("qOffsets", own_buf
) == 0)
2280 CORE_ADDR text
, data
;
2282 require_running_or_return (own_buf
);
2283 if (the_target
->read_offsets (&text
, &data
))
2284 sprintf (own_buf
, "Text=%lX;Data=%lX;Bss=%lX",
2285 (long)text
, (long)data
, (long)data
);
2287 write_enn (own_buf
);
2292 /* Protocol features query. */
2293 if (startswith (own_buf
, "qSupported")
2294 && (own_buf
[10] == ':' || own_buf
[10] == '\0'))
2296 char *p
= &own_buf
[10];
2297 int gdb_supports_qRelocInsn
= 0;
2299 /* Process each feature being provided by GDB. The first
2300 feature will follow a ':', and latter features will follow
2304 std::vector
<std::string
> qsupported
;
2305 std::vector
<const char *> unknowns
;
2307 /* Two passes, to avoid nested strtok calls in
2308 target_process_qsupported. */
2310 for (p
= strtok_r (p
+ 1, ";", &saveptr
);
2312 p
= strtok_r (NULL
, ";", &saveptr
))
2313 qsupported
.emplace_back (p
);
2315 for (const std::string
&feature
: qsupported
)
2317 if (feature
== "multiprocess+")
2319 /* GDB supports and wants multi-process support if
2321 if (target_supports_multi_process ())
2322 cs
.multi_process
= 1;
2324 else if (feature
== "qRelocInsn+")
2326 /* GDB supports relocate instruction requests. */
2327 gdb_supports_qRelocInsn
= 1;
2329 else if (feature
== "swbreak+")
2331 /* GDB wants us to report whether a trap is caused
2332 by a software breakpoint and for us to handle PC
2333 adjustment if necessary on this target. */
2334 if (target_supports_stopped_by_sw_breakpoint ())
2335 cs
.swbreak_feature
= 1;
2337 else if (feature
== "hwbreak+")
2339 /* GDB wants us to report whether a trap is caused
2340 by a hardware breakpoint. */
2341 if (target_supports_stopped_by_hw_breakpoint ())
2342 cs
.hwbreak_feature
= 1;
2344 else if (feature
== "fork-events+")
2346 /* GDB supports and wants fork events if possible. */
2347 if (target_supports_fork_events ())
2348 cs
.report_fork_events
= 1;
2350 else if (feature
== "vfork-events+")
2352 /* GDB supports and wants vfork events if possible. */
2353 if (target_supports_vfork_events ())
2354 cs
.report_vfork_events
= 1;
2356 else if (feature
== "exec-events+")
2358 /* GDB supports and wants exec events if possible. */
2359 if (target_supports_exec_events ())
2360 cs
.report_exec_events
= 1;
2362 else if (feature
== "vContSupported+")
2363 cs
.vCont_supported
= 1;
2364 else if (feature
== "QThreadEvents+")
2366 else if (feature
== "no-resumed+")
2368 /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
2370 report_no_resumed
= true;
2372 else if (feature
== "memory-tagging+")
2374 /* GDB supports memory tagging features. */
2375 if (target_supports_memory_tagging ())
2376 cs
.memory_tagging_feature
= true;
2380 /* Move the unknown features all together. */
2381 unknowns
.push_back (feature
.c_str ());
2385 /* Give the target backend a chance to process the unknown
2387 target_process_qsupported (unknowns
);
2391 "PacketSize=%x;QPassSignals+;QProgramSignals+;"
2392 "QStartupWithShell+;QEnvironmentHexEncoded+;"
2393 "QEnvironmentReset+;QEnvironmentUnset+;"
2397 if (target_supports_catch_syscall ())
2398 strcat (own_buf
, ";QCatchSyscalls+");
2400 if (the_target
->supports_qxfer_libraries_svr4 ())
2401 strcat (own_buf
, ";qXfer:libraries-svr4:read+"
2402 ";augmented-libraries-svr4-read+");
2405 /* We do not have any hook to indicate whether the non-SVR4 target
2406 backend supports qXfer:libraries:read, so always report it. */
2407 strcat (own_buf
, ";qXfer:libraries:read+");
2410 if (the_target
->supports_read_auxv ())
2411 strcat (own_buf
, ";qXfer:auxv:read+");
2413 if (the_target
->supports_qxfer_siginfo ())
2414 strcat (own_buf
, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2416 if (the_target
->supports_read_loadmap ())
2417 strcat (own_buf
, ";qXfer:fdpic:read+");
2419 /* We always report qXfer:features:read, as targets may
2420 install XML files on a subsequent call to arch_setup.
2421 If we reported to GDB on startup that we don't support
2422 qXfer:feature:read at all, we will never be re-queried. */
2423 strcat (own_buf
, ";qXfer:features:read+");
2425 if (cs
.transport_is_reliable
)
2426 strcat (own_buf
, ";QStartNoAckMode+");
2428 if (the_target
->supports_qxfer_osdata ())
2429 strcat (own_buf
, ";qXfer:osdata:read+");
2431 if (target_supports_multi_process ())
2432 strcat (own_buf
, ";multiprocess+");
2434 if (target_supports_fork_events ())
2435 strcat (own_buf
, ";fork-events+");
2437 if (target_supports_vfork_events ())
2438 strcat (own_buf
, ";vfork-events+");
2440 if (target_supports_exec_events ())
2441 strcat (own_buf
, ";exec-events+");
2443 if (target_supports_non_stop ())
2444 strcat (own_buf
, ";QNonStop+");
2446 if (target_supports_disable_randomization ())
2447 strcat (own_buf
, ";QDisableRandomization+");
2449 strcat (own_buf
, ";qXfer:threads:read+");
2451 if (target_supports_tracepoints ())
2453 strcat (own_buf
, ";ConditionalTracepoints+");
2454 strcat (own_buf
, ";TraceStateVariables+");
2455 strcat (own_buf
, ";TracepointSource+");
2456 strcat (own_buf
, ";DisconnectedTracing+");
2457 if (gdb_supports_qRelocInsn
&& target_supports_fast_tracepoints ())
2458 strcat (own_buf
, ";FastTracepoints+");
2459 strcat (own_buf
, ";StaticTracepoints+");
2460 strcat (own_buf
, ";InstallInTrace+");
2461 strcat (own_buf
, ";qXfer:statictrace:read+");
2462 strcat (own_buf
, ";qXfer:traceframe-info:read+");
2463 strcat (own_buf
, ";EnableDisableTracepoints+");
2464 strcat (own_buf
, ";QTBuffer:size+");
2465 strcat (own_buf
, ";tracenz+");
2468 if (target_supports_hardware_single_step ()
2469 || target_supports_software_single_step () )
2471 strcat (own_buf
, ";ConditionalBreakpoints+");
2473 strcat (own_buf
, ";BreakpointCommands+");
2475 if (target_supports_agent ())
2476 strcat (own_buf
, ";QAgent+");
2478 if (the_target
->supports_btrace ())
2479 supported_btrace_packets (own_buf
);
2481 if (target_supports_stopped_by_sw_breakpoint ())
2482 strcat (own_buf
, ";swbreak+");
2484 if (target_supports_stopped_by_hw_breakpoint ())
2485 strcat (own_buf
, ";hwbreak+");
2487 if (the_target
->supports_pid_to_exec_file ())
2488 strcat (own_buf
, ";qXfer:exec-file:read+");
2490 strcat (own_buf
, ";vContSupported+");
2492 strcat (own_buf
, ";QThreadEvents+");
2494 strcat (own_buf
, ";no-resumed+");
2496 if (target_supports_memory_tagging ())
2497 strcat (own_buf
, ";memory-tagging+");
2499 /* Reinitialize components as needed for the new connection. */
2500 hostio_handle_new_gdb_connection ();
2501 target_handle_new_gdb_connection ();
2506 /* Thread-local storage support. */
2507 if (the_target
->supports_get_tls_address ()
2508 && startswith (own_buf
, "qGetTLSAddr:"))
2510 char *p
= own_buf
+ 12;
2511 CORE_ADDR parts
[2], address
= 0;
2513 ptid_t ptid
= null_ptid
;
2515 require_running_or_return (own_buf
);
2517 for (i
= 0; i
< 3; i
++)
2525 p2
= strchr (p
, ',');
2538 ptid
= read_ptid (p
, NULL
);
2540 decode_address (&parts
[i
- 1], p
, len
);
2544 if (p
!= NULL
|| i
< 3)
2548 struct thread_info
*thread
= find_thread_ptid (ptid
);
2553 err
= the_target
->get_tls_address (thread
, parts
[0], parts
[1],
2559 strcpy (own_buf
, paddress(address
));
2564 write_enn (own_buf
);
2568 /* Otherwise, pretend we do not understand this packet. */
2571 /* Windows OS Thread Information Block address support. */
2572 if (the_target
->supports_get_tib_address ()
2573 && startswith (own_buf
, "qGetTIBAddr:"))
2578 ptid_t ptid
= read_ptid (own_buf
+ 12, &annex
);
2580 n
= the_target
->get_tib_address (ptid
, &tlb
);
2583 strcpy (own_buf
, paddress(tlb
));
2588 write_enn (own_buf
);
2594 /* Handle "monitor" commands. */
2595 if (startswith (own_buf
, "qRcmd,"))
2597 char *mon
= (char *) malloc (PBUFSIZ
);
2598 int len
= strlen (own_buf
+ 6);
2602 write_enn (own_buf
);
2607 || hex2bin (own_buf
+ 6, (gdb_byte
*) mon
, len
/ 2) != len
/ 2)
2609 write_enn (own_buf
);
2613 mon
[len
/ 2] = '\0';
2617 if (the_target
->handle_monitor_command (mon
) == 0)
2618 /* Default processing. */
2619 handle_monitor_command (mon
, own_buf
);
2625 if (startswith (own_buf
, "qSearch:memory:"))
2627 require_running_or_return (own_buf
);
2628 handle_search_memory (own_buf
, packet_len
);
2632 if (strcmp (own_buf
, "qAttached") == 0
2633 || startswith (own_buf
, "qAttached:"))
2635 struct process_info
*process
;
2637 if (own_buf
[sizeof ("qAttached") - 1])
2639 int pid
= strtoul (own_buf
+ sizeof ("qAttached:") - 1, NULL
, 16);
2640 process
= find_process_pid (pid
);
2644 require_running_or_return (own_buf
);
2645 process
= current_process ();
2648 if (process
== NULL
)
2650 write_enn (own_buf
);
2654 strcpy (own_buf
, process
->attached
? "1" : "0");
2658 if (startswith (own_buf
, "qCRC:"))
2660 /* CRC check (compare-section). */
2664 unsigned long long crc
;
2666 require_running_or_return (own_buf
);
2667 comma
= unpack_varlen_hex (own_buf
+ 5, &base
);
2668 if (*comma
++ != ',')
2670 write_enn (own_buf
);
2673 len
= strtoul (comma
, NULL
, 16);
2674 crc
= crc32 (base
, len
, 0xffffffff);
2675 /* Check for memory failure. */
2676 if (crc
== (unsigned long long) -1)
2678 write_enn (own_buf
);
2681 sprintf (own_buf
, "C%lx", (unsigned long) crc
);
2685 if (handle_qxfer (own_buf
, packet_len
, new_packet_len_p
))
2688 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf
))
2691 /* Handle fetch memory tags packets. */
2692 if (startswith (own_buf
, "qMemTags:")
2693 && target_supports_memory_tagging ())
2695 gdb::byte_vector tags
;
2700 require_running_or_return (own_buf
);
2702 parse_fetch_memtags_request (own_buf
, &addr
, &len
, &type
);
2704 bool ret
= the_target
->fetch_memtags (addr
, len
, tags
, type
);
2707 ret
= create_fetch_memtags_reply (own_buf
, tags
);
2710 write_enn (own_buf
);
2712 *new_packet_len_p
= strlen (own_buf
);
2716 /* Otherwise we didn't know what packet it was. Say we didn't
2721 static void gdb_wants_all_threads_stopped (void);
2722 static void resume (struct thread_resume
*actions
, size_t n
);
2724 /* The callback that is passed to visit_actioned_threads. */
2725 typedef int (visit_actioned_threads_callback_ftype
)
2726 (const struct thread_resume
*, struct thread_info
*);
2728 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
2729 true if CALLBACK returns true. Returns false if no matching thread
2730 is found or CALLBACK results false.
2731 Note: This function is itself a callback for find_thread. */
2734 visit_actioned_threads (thread_info
*thread
,
2735 const struct thread_resume
*actions
,
2737 visit_actioned_threads_callback_ftype
*callback
)
2739 for (size_t i
= 0; i
< num_actions
; i
++)
2741 const struct thread_resume
*action
= &actions
[i
];
2743 if (action
->thread
== minus_one_ptid
2744 || action
->thread
== thread
->id
2745 || ((action
->thread
.pid ()
2746 == thread
->id
.pid ())
2747 && action
->thread
.lwp () == -1))
2749 if ((*callback
) (action
, thread
))
2757 /* Callback for visit_actioned_threads. If the thread has a pending
2758 status to report, report it now. */
2761 handle_pending_status (const struct thread_resume
*resumption
,
2762 struct thread_info
*thread
)
2764 client_state
&cs
= get_client_state ();
2765 if (thread
->status_pending_p
)
2767 thread
->status_pending_p
= 0;
2769 cs
.last_status
= thread
->last_status
;
2770 cs
.last_ptid
= thread
->id
;
2771 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, cs
.last_status
);
2777 /* Parse vCont packets. */
2779 handle_v_cont (char *own_buf
)
2783 struct thread_resume
*resume_info
;
2784 struct thread_resume default_action
{ null_ptid
};
2786 /* Count the number of semicolons in the packet. There should be one
2787 for every action. */
2793 p
= strchr (p
, ';');
2796 resume_info
= (struct thread_resume
*) malloc (n
* sizeof (resume_info
[0]));
2797 if (resume_info
== NULL
)
2805 memset (&resume_info
[i
], 0, sizeof resume_info
[i
]);
2807 if (p
[0] == 's' || p
[0] == 'S')
2808 resume_info
[i
].kind
= resume_step
;
2809 else if (p
[0] == 'r')
2810 resume_info
[i
].kind
= resume_step
;
2811 else if (p
[0] == 'c' || p
[0] == 'C')
2812 resume_info
[i
].kind
= resume_continue
;
2813 else if (p
[0] == 't')
2814 resume_info
[i
].kind
= resume_stop
;
2818 if (p
[0] == 'S' || p
[0] == 'C')
2821 int sig
= strtol (p
+ 1, &q
, 16);
2826 if (!gdb_signal_to_host_p ((enum gdb_signal
) sig
))
2828 resume_info
[i
].sig
= gdb_signal_to_host ((enum gdb_signal
) sig
);
2830 else if (p
[0] == 'r')
2834 p
= unpack_varlen_hex (p
+ 1, &addr
);
2835 resume_info
[i
].step_range_start
= addr
;
2840 p
= unpack_varlen_hex (p
+ 1, &addr
);
2841 resume_info
[i
].step_range_end
= addr
;
2850 resume_info
[i
].thread
= minus_one_ptid
;
2851 default_action
= resume_info
[i
];
2853 /* Note: we don't increment i here, we'll overwrite this entry
2854 the next time through. */
2856 else if (p
[0] == ':')
2859 ptid_t ptid
= read_ptid (p
+ 1, &q
);
2864 if (p
[0] != ';' && p
[0] != 0)
2867 resume_info
[i
].thread
= ptid
;
2874 resume_info
[i
] = default_action
;
2876 resume (resume_info
, n
);
2881 write_enn (own_buf
);
2886 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
2889 resume (struct thread_resume
*actions
, size_t num_actions
)
2891 client_state
&cs
= get_client_state ();
2894 /* Check if among the threads that GDB wants actioned, there's
2895 one with a pending status to report. If so, skip actually
2896 resuming/stopping and report the pending event
2899 thread_info
*thread_with_status
= find_thread ([&] (thread_info
*thread
)
2901 return visit_actioned_threads (thread
, actions
, num_actions
,
2902 handle_pending_status
);
2905 if (thread_with_status
!= NULL
)
2911 the_target
->resume (actions
, num_actions
);
2914 write_ok (cs
.own_buf
);
2917 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
, 0, 1);
2919 if (cs
.last_status
.kind () == TARGET_WAITKIND_NO_RESUMED
2920 && !report_no_resumed
)
2922 /* The client does not support this stop reply. At least
2924 sprintf (cs
.own_buf
, "E.No unwaited-for children left.");
2925 disable_async_io ();
2929 if (cs
.last_status
.kind () != TARGET_WAITKIND_EXITED
2930 && cs
.last_status
.kind () != TARGET_WAITKIND_SIGNALLED
2931 && cs
.last_status
.kind () != TARGET_WAITKIND_NO_RESUMED
)
2932 current_thread
->last_status
= cs
.last_status
;
2934 /* From the client's perspective, all-stop mode always stops all
2935 threads implicitly (and the target backend has already done
2936 so by now). Tag all threads as "want-stopped", so we don't
2937 resume them implicitly without the client telling us to. */
2938 gdb_wants_all_threads_stopped ();
2939 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, cs
.last_status
);
2940 disable_async_io ();
2942 if (cs
.last_status
.kind () == TARGET_WAITKIND_EXITED
2943 || cs
.last_status
.kind () == TARGET_WAITKIND_SIGNALLED
)
2944 target_mourn_inferior (cs
.last_ptid
);
2948 /* Attach to a new program. */
2950 handle_v_attach (char *own_buf
)
2952 client_state
&cs
= get_client_state ();
2955 pid
= strtol (own_buf
+ 8, NULL
, 16);
2956 if (pid
!= 0 && attach_inferior (pid
) == 0)
2958 /* Don't report shared library events after attaching, even if
2959 some libraries are preloaded. GDB will always poll the
2960 library list. Avoids the "stopped by shared library event"
2961 notice on the GDB side. */
2962 current_process ()->dlls_changed
= false;
2966 /* In non-stop, we don't send a resume reply. Stop events
2967 will follow up using the normal notification
2972 prepare_resume_reply (own_buf
, cs
.last_ptid
, cs
.last_status
);
2975 write_enn (own_buf
);
2978 /* Run a new program. */
2980 handle_v_run (char *own_buf
)
2982 client_state
&cs
= get_client_state ();
2984 std::vector
<char *> new_argv
;
2985 char *new_program_name
= NULL
;
2988 for (i
= 0, p
= own_buf
+ strlen ("vRun;"); *p
; p
= next_p
, ++i
)
2990 next_p
= strchr (p
, ';');
2992 next_p
= p
+ strlen (p
);
2994 if (i
== 0 && p
== next_p
)
2996 /* No program specified. */
2997 new_program_name
= NULL
;
2999 else if (p
== next_p
)
3001 /* Empty argument. */
3002 new_argv
.push_back (xstrdup (""));
3006 size_t len
= (next_p
- p
) / 2;
3007 /* ARG is the unquoted argument received via the RSP. */
3008 char *arg
= (char *) xmalloc (len
+ 1);
3009 /* FULL_ARGS will contain the quoted version of ARG. */
3010 char *full_arg
= (char *) xmalloc ((len
+ 1) * 2);
3011 /* These are pointers used to navigate the strings above. */
3012 char *tmp_arg
= arg
;
3013 char *tmp_full_arg
= full_arg
;
3016 hex2bin (p
, (gdb_byte
*) arg
, len
);
3019 while (*tmp_arg
!= '\0')
3025 *tmp_full_arg
= '\'';
3031 /* Quote single quote. */
3032 *tmp_full_arg
= '\\';
3040 *tmp_full_arg
= *tmp_arg
;
3046 *tmp_full_arg
++ = '\'';
3048 /* Finish FULL_ARG and push it into the vector containing
3050 *tmp_full_arg
= '\0';
3052 new_program_name
= full_arg
;
3054 new_argv
.push_back (full_arg
);
3061 if (new_program_name
== NULL
)
3063 /* GDB didn't specify a program to run. Use the program from the
3064 last run with the new argument list. */
3065 if (program_path
.get () == NULL
)
3067 write_enn (own_buf
);
3068 free_vector_argv (new_argv
);
3073 program_path
.set (new_program_name
);
3075 /* Free the old argv and install the new one. */
3076 free_vector_argv (program_args
);
3077 program_args
= new_argv
;
3079 target_create_inferior (program_path
.get (), program_args
);
3081 if (cs
.last_status
.kind () == TARGET_WAITKIND_STOPPED
)
3083 prepare_resume_reply (own_buf
, cs
.last_ptid
, cs
.last_status
);
3085 /* In non-stop, sending a resume reply doesn't set the general
3086 thread, but GDB assumes a vRun sets it (this is so GDB can
3087 query which is the main thread of the new inferior. */
3089 cs
.general_thread
= cs
.last_ptid
;
3092 write_enn (own_buf
);
3097 handle_v_kill (char *own_buf
)
3099 client_state
&cs
= get_client_state ();
3101 char *p
= &own_buf
[6];
3102 if (cs
.multi_process
)
3103 pid
= strtol (p
, NULL
, 16);
3107 process_info
*proc
= find_process_pid (pid
);
3109 if (proc
!= nullptr && kill_inferior (proc
) == 0)
3111 cs
.last_status
.set_signalled (GDB_SIGNAL_KILL
);
3112 cs
.last_ptid
= ptid_t (pid
);
3113 discard_queued_stop_replies (cs
.last_ptid
);
3117 write_enn (own_buf
);
3120 /* Handle all of the extended 'v' packets. */
3122 handle_v_requests (char *own_buf
, int packet_len
, int *new_packet_len
)
3124 client_state
&cs
= get_client_state ();
3125 if (!disable_packet_vCont
)
3127 if (strcmp (own_buf
, "vCtrlC") == 0)
3129 the_target
->request_interrupt ();
3134 if (startswith (own_buf
, "vCont;"))
3136 handle_v_cont (own_buf
);
3140 if (startswith (own_buf
, "vCont?"))
3142 strcpy (own_buf
, "vCont;c;C;t");
3144 if (target_supports_hardware_single_step ()
3145 || target_supports_software_single_step ()
3146 || !cs
.vCont_supported
)
3148 /* If target supports single step either by hardware or by
3149 software, add actions s and S to the list of supported
3150 actions. On the other hand, if GDB doesn't request the
3151 supported vCont actions in qSupported packet, add s and
3152 S to the list too. */
3153 own_buf
= own_buf
+ strlen (own_buf
);
3154 strcpy (own_buf
, ";s;S");
3157 if (target_supports_range_stepping ())
3159 own_buf
= own_buf
+ strlen (own_buf
);
3160 strcpy (own_buf
, ";r");
3166 if (startswith (own_buf
, "vFile:")
3167 && handle_vFile (own_buf
, packet_len
, new_packet_len
))
3170 if (startswith (own_buf
, "vAttach;"))
3172 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3174 fprintf (stderr
, "Already debugging a process\n");
3175 write_enn (own_buf
);
3178 handle_v_attach (own_buf
);
3182 if (startswith (own_buf
, "vRun;"))
3184 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3186 fprintf (stderr
, "Already debugging a process\n");
3187 write_enn (own_buf
);
3190 handle_v_run (own_buf
);
3194 if (startswith (own_buf
, "vKill;"))
3196 if (!target_running ())
3198 fprintf (stderr
, "No process to kill\n");
3199 write_enn (own_buf
);
3202 handle_v_kill (own_buf
);
3206 if (handle_notif_ack (own_buf
, packet_len
))
3209 /* Otherwise we didn't know what packet it was. Say we didn't
3215 /* Resume thread and wait for another event. In non-stop mode,
3216 don't really wait here, but return immediatelly to the event
3219 myresume (char *own_buf
, int step
, int sig
)
3221 client_state
&cs
= get_client_state ();
3222 struct thread_resume resume_info
[2];
3224 int valid_cont_thread
;
3226 valid_cont_thread
= (cs
.cont_thread
!= null_ptid
3227 && cs
.cont_thread
!= minus_one_ptid
);
3229 if (step
|| sig
|| valid_cont_thread
)
3231 resume_info
[0].thread
= current_ptid
;
3233 resume_info
[0].kind
= resume_step
;
3235 resume_info
[0].kind
= resume_continue
;
3236 resume_info
[0].sig
= sig
;
3240 if (!valid_cont_thread
)
3242 resume_info
[n
].thread
= minus_one_ptid
;
3243 resume_info
[n
].kind
= resume_continue
;
3244 resume_info
[n
].sig
= 0;
3248 resume (resume_info
, n
);
3251 /* Callback for for_each_thread. Make a new stop reply for each
3255 queue_stop_reply_callback (thread_info
*thread
)
3257 /* For now, assume targets that don't have this callback also don't
3258 manage the thread's last_status field. */
3259 if (!the_target
->supports_thread_stopped ())
3261 struct vstop_notif
*new_notif
= new struct vstop_notif
;
3263 new_notif
->ptid
= thread
->id
;
3264 new_notif
->status
= thread
->last_status
;
3265 /* Pass the last stop reply back to GDB, but don't notify
3267 notif_event_enque (¬if_stop
, new_notif
);
3271 if (target_thread_stopped (thread
))
3273 threads_debug_printf
3274 ("Reporting thread %s as already stopped with %s",
3275 target_pid_to_str (thread
->id
).c_str (),
3276 thread
->last_status
.to_string ().c_str ());
3278 gdb_assert (thread
->last_status
.kind () != TARGET_WAITKIND_IGNORE
);
3280 /* Pass the last stop reply back to GDB, but don't notify
3282 queue_stop_reply (thread
->id
, thread
->last_status
);
3287 /* Set this inferior threads's state as "want-stopped". We won't
3288 resume this thread until the client gives us another action for
3292 gdb_wants_thread_stopped (thread_info
*thread
)
3294 thread
->last_resume_kind
= resume_stop
;
3296 if (thread
->last_status
.kind () == TARGET_WAITKIND_IGNORE
)
3298 /* Most threads are stopped implicitly (all-stop); tag that with
3300 thread
->last_status
.set_stopped (GDB_SIGNAL_0
);
3304 /* Set all threads' states as "want-stopped". */
3307 gdb_wants_all_threads_stopped (void)
3309 for_each_thread (gdb_wants_thread_stopped
);
3312 /* Callback for for_each_thread. If the thread is stopped with an
3313 interesting event, mark it as having a pending event. */
3316 set_pending_status_callback (thread_info
*thread
)
3318 if (thread
->last_status
.kind () != TARGET_WAITKIND_STOPPED
3319 || (thread
->last_status
.sig () != GDB_SIGNAL_0
3320 /* A breakpoint, watchpoint or finished step from a previous
3321 GDB run isn't considered interesting for a new GDB run.
3322 If we left those pending, the new GDB could consider them
3323 random SIGTRAPs. This leaves out real async traps. We'd
3324 have to peek into the (target-specific) siginfo to
3325 distinguish those. */
3326 && thread
->last_status
.sig () != GDB_SIGNAL_TRAP
))
3327 thread
->status_pending_p
= 1;
3330 /* Status handler for the '?' packet. */
3333 handle_status (char *own_buf
)
3335 client_state
&cs
= get_client_state ();
3337 /* GDB is connected, don't forward events to the target anymore. */
3338 for_each_process ([] (process_info
*process
) {
3339 process
->gdb_detached
= 0;
3342 /* In non-stop mode, we must send a stop reply for each stopped
3343 thread. In all-stop mode, just send one for the first stopped
3348 for_each_thread (queue_stop_reply_callback
);
3350 /* The first is sent immediatly. OK is sent if there is no
3351 stopped thread, which is the same handling of the vStopped
3352 packet (by design). */
3353 notif_write_event (¬if_stop
, cs
.own_buf
);
3357 thread_info
*thread
= NULL
;
3359 target_pause_all (false);
3360 target_stabilize_threads ();
3361 gdb_wants_all_threads_stopped ();
3363 /* We can only report one status, but we might be coming out of
3364 non-stop -- if more than one thread is stopped with
3365 interesting events, leave events for the threads we're not
3366 reporting now pending. They'll be reported the next time the
3367 threads are resumed. Start by marking all interesting events
3369 for_each_thread (set_pending_status_callback
);
3371 /* Prefer the last thread that reported an event to GDB (even if
3372 that was a GDB_SIGNAL_TRAP). */
3373 if (cs
.last_status
.kind () != TARGET_WAITKIND_IGNORE
3374 && cs
.last_status
.kind () != TARGET_WAITKIND_EXITED
3375 && cs
.last_status
.kind () != TARGET_WAITKIND_SIGNALLED
)
3376 thread
= find_thread_ptid (cs
.last_ptid
);
3378 /* If the last event thread is not found for some reason, look
3379 for some other thread that might have an event to report. */
3381 thread
= find_thread ([] (thread_info
*thr_arg
)
3383 return thr_arg
->status_pending_p
;
3386 /* If we're still out of luck, simply pick the first thread in
3389 thread
= get_first_thread ();
3393 struct thread_info
*tp
= (struct thread_info
*) thread
;
3395 /* We're reporting this event, so it's no longer
3397 tp
->status_pending_p
= 0;
3399 /* GDB assumes the current thread is the thread we're
3400 reporting the status for. */
3401 cs
.general_thread
= thread
->id
;
3402 set_desired_thread ();
3404 gdb_assert (tp
->last_status
.kind () != TARGET_WAITKIND_IGNORE
);
3405 prepare_resume_reply (own_buf
, tp
->id
, tp
->last_status
);
3408 strcpy (own_buf
, "W00");
3413 gdbserver_version (void)
3415 printf ("GNU gdbserver %s%s\n"
3416 "Copyright (C) 2022 Free Software Foundation, Inc.\n"
3417 "gdbserver is free software, covered by the "
3418 "GNU General Public License.\n"
3419 "This gdbserver was configured as \"%s\"\n",
3420 PKGVERSION
, version
, host_name
);
3424 gdbserver_usage (FILE *stream
)
3426 fprintf (stream
, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3427 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3428 "\tgdbserver [OPTIONS] --multi COMM\n"
3430 "COMM may either be a tty device (for serial debugging),\n"
3431 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3432 "stdin/stdout of gdbserver.\n"
3433 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3434 "PID is the process ID to attach to, when --attach is specified.\n"
3436 "Operating modes:\n"
3438 " --attach Attach to running process PID.\n"
3439 " --multi Start server without a specific program, and\n"
3440 " only quit when explicitly commanded.\n"
3441 " --once Exit after the first connection has closed.\n"
3442 " --help Print this message and then exit.\n"
3443 " --version Display version information and exit.\n"
3447 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3448 " --disable-randomization\n"
3449 " Run PROG with address space randomization disabled.\n"
3450 " --no-disable-randomization\n"
3451 " Don't disable address space randomization when\n"
3453 " --startup-with-shell\n"
3454 " Start PROG using a shell. I.e., execs a shell that\n"
3455 " then execs PROG. (default)\n"
3456 " --no-startup-with-shell\n"
3457 " Exec PROG directly instead of using a shell.\n"
3458 " Disables argument globbing and variable substitution\n"
3459 " on UNIX-like systems.\n"
3463 " --debug Enable general debugging output.\n"
3464 " --debug-format=OPT1[,OPT2,...]\n"
3465 " Specify extra content in debugging output.\n"
3470 " --remote-debug Enable remote protocol debugging output.\n"
3471 " --event-loop-debug Enable event loop debugging output.\n"
3472 " --disable-packet=OPT1[,OPT2,...]\n"
3473 " Disable support for RSP packets or features.\n"
3475 " vCont, T, Tthread, qC, qfThreadInfo and \n"
3476 " threads (disable all threading packets).\n"
3478 "For more information, consult the GDB manual (available as on-line \n"
3479 "info or a printed manual).\n");
3480 if (REPORT_BUGS_TO
[0] && stream
== stdout
)
3481 fprintf (stream
, "Report bugs to \"%s\".\n", REPORT_BUGS_TO
);
3485 gdbserver_show_disableable (FILE *stream
)
3487 fprintf (stream
, "Disableable packets:\n"
3488 " vCont \tAll vCont packets\n"
3489 " qC \tQuerying the current thread\n"
3490 " qfThreadInfo\tThread listing\n"
3491 " Tthread \tPassing the thread specifier in the "
3492 "T stop reply packet\n"
3493 " threads \tAll of the above\n"
3494 " T \tAll 'T' packets\n");
3497 /* Start up the event loop. This is the entry point to the event
3503 /* Loop until there is nothing to do. This is the entry point to
3504 the event loop engine. If nothing is ready at this time, wait
3505 for something to happen (via wait_for_event), then process it.
3506 Return when there are no longer event sources to wait for. */
3508 keep_processing_events
= true;
3509 while (keep_processing_events
)
3511 /* Any events already waiting in the queue? */
3512 int res
= gdb_do_one_event ();
3514 /* Was there an error? */
3519 /* We are done with the event loop. There are no more event sources
3520 to listen to. So we exit gdbserver. */
3524 kill_inferior_callback (process_info
*process
)
3526 kill_inferior (process
);
3527 discard_queued_stop_replies (ptid_t (process
->pid
));
3530 /* Call this when exiting gdbserver with possible inferiors that need
3531 to be killed or detached from. */
3534 detach_or_kill_for_exit (void)
3536 /* First print a list of the inferiors we will be killing/detaching.
3537 This is to assist the user, for example, in case the inferior unexpectedly
3538 dies after we exit: did we screw up or did the inferior exit on its own?
3539 Having this info will save some head-scratching. */
3541 if (have_started_inferiors_p ())
3543 fprintf (stderr
, "Killing process(es):");
3545 for_each_process ([] (process_info
*process
) {
3546 if (!process
->attached
)
3547 fprintf (stderr
, " %d", process
->pid
);
3550 fprintf (stderr
, "\n");
3552 if (have_attached_inferiors_p ())
3554 fprintf (stderr
, "Detaching process(es):");
3556 for_each_process ([] (process_info
*process
) {
3557 if (process
->attached
)
3558 fprintf (stderr
, " %d", process
->pid
);
3561 fprintf (stderr
, "\n");
3564 /* Now we can kill or detach the inferiors. */
3565 for_each_process ([] (process_info
*process
) {
3566 int pid
= process
->pid
;
3568 if (process
->attached
)
3569 detach_inferior (process
);
3571 kill_inferior (process
);
3573 discard_queued_stop_replies (ptid_t (pid
));
3577 /* Value that will be passed to exit(3) when gdbserver exits. */
3578 static int exit_code
;
3580 /* Wrapper for detach_or_kill_for_exit that catches and prints
3584 detach_or_kill_for_exit_cleanup ()
3588 detach_or_kill_for_exit ();
3590 catch (const gdb_exception
&exception
)
3593 fprintf (stderr
, "Detach or kill failed: %s\n",
3601 namespace selftests
{
3604 test_memory_tagging_functions (void)
3606 /* Setup testing. */
3607 gdb::char_vector packet
;
3608 gdb::byte_vector tags
, bv
;
3609 std::string expected
;
3610 packet
.resize (32000);
3615 /* Test parsing a qMemTags request. */
3617 /* Valid request, addr, len and type updated. */
3621 strcpy (packet
.data (), "qMemTags:0,0:0");
3622 parse_fetch_memtags_request (packet
.data (), &addr
, &len
, &type
);
3623 SELF_CHECK (addr
== 0 && len
== 0 && type
== 0);
3625 /* Valid request, addr, len and type updated. */
3629 strcpy (packet
.data (), "qMemTags:deadbeef,ff:5");
3630 parse_fetch_memtags_request (packet
.data (), &addr
, &len
, &type
);
3631 SELF_CHECK (addr
== 0xdeadbeef && len
== 255 && type
== 5);
3633 /* Test creating a qMemTags reply. */
3635 /* Non-empty tag data. */
3638 for (int i
= 0; i
< 5; i
++)
3641 expected
= "m0001020304";
3642 SELF_CHECK (create_fetch_memtags_reply (packet
.data (), bv
) == true);
3643 SELF_CHECK (strcmp (packet
.data (), expected
.c_str ()) == 0);
3645 /* Test parsing a QMemTags request. */
3647 /* Valid request and empty tag data: addr, len, type and tags updated. */
3652 strcpy (packet
.data (), "QMemTags:0,0:0:");
3653 SELF_CHECK (parse_store_memtags_request (packet
.data (),
3654 &addr
, &len
, tags
, &type
) == true);
3655 SELF_CHECK (addr
== 0 && len
== 0 && type
== 0 && tags
.size () == 0);
3657 /* Valid request and non-empty tag data: addr, len, type
3658 and tags updated. */
3663 strcpy (packet
.data (),
3664 "QMemTags:deadbeef,ff:5:0001020304");
3665 SELF_CHECK (parse_store_memtags_request (packet
.data (), &addr
, &len
, tags
,
3667 SELF_CHECK (addr
== 0xdeadbeef && len
== 255 && type
== 5
3668 && tags
.size () == 5);
3671 } // namespace selftests
3672 #endif /* GDB_SELF_TEST */
3674 /* Main function. This is called by the real "main" function,
3675 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
3677 static void ATTRIBUTE_NORETURN
3678 captured_main (int argc
, char *argv
[])
3683 const char *port
= NULL
;
3684 char **next_arg
= &argv
[1];
3685 volatile int multi_mode
= 0;
3686 volatile int attach
= 0;
3688 bool selftest
= false;
3690 std::vector
<const char *> selftest_filters
;
3692 selftests::register_test ("remote_memory_tagging",
3693 selftests::test_memory_tagging_functions
);
3696 current_directory
= getcwd (NULL
, 0);
3697 client_state
&cs
= get_client_state ();
3699 if (current_directory
== NULL
)
3701 error (_("Could not find current working directory: %s"),
3702 safe_strerror (errno
));
3705 while (*next_arg
!= NULL
&& **next_arg
== '-')
3707 if (strcmp (*next_arg
, "--version") == 0)
3709 gdbserver_version ();
3712 else if (strcmp (*next_arg
, "--help") == 0)
3714 gdbserver_usage (stdout
);
3717 else if (strcmp (*next_arg
, "--attach") == 0)
3719 else if (strcmp (*next_arg
, "--multi") == 0)
3721 else if (strcmp (*next_arg
, "--wrapper") == 0)
3728 while (*next_arg
!= NULL
&& strcmp (*next_arg
, "--") != 0)
3730 wrapper_argv
+= *next_arg
;
3731 wrapper_argv
+= ' ';
3735 if (!wrapper_argv
.empty ())
3737 /* Erase the last whitespace. */
3738 wrapper_argv
.erase (wrapper_argv
.end () - 1);
3741 if (next_arg
== tmp
|| *next_arg
== NULL
)
3743 gdbserver_usage (stderr
);
3747 /* Consume the "--". */
3750 else if (strcmp (*next_arg
, "--debug") == 0)
3751 debug_threads
= true;
3752 else if (startswith (*next_arg
, "--debug-format="))
3754 std::string error_msg
3755 = parse_debug_format_options ((*next_arg
)
3756 + sizeof ("--debug-format=") - 1, 0);
3758 if (!error_msg
.empty ())
3760 fprintf (stderr
, "%s", error_msg
.c_str ());
3764 else if (strcmp (*next_arg
, "--remote-debug") == 0)
3765 remote_debug
= true;
3766 else if (strcmp (*next_arg
, "--event-loop-debug") == 0)
3767 debug_event_loop
= debug_event_loop_kind::ALL
;
3768 else if (startswith (*next_arg
, "--debug-file="))
3769 debug_set_output ((*next_arg
) + sizeof ("--debug-file=") -1);
3770 else if (strcmp (*next_arg
, "--disable-packet") == 0)
3772 gdbserver_show_disableable (stdout
);
3775 else if (startswith (*next_arg
, "--disable-packet="))
3777 char *packets
= *next_arg
+= sizeof ("--disable-packet=") - 1;
3779 for (char *tok
= strtok_r (packets
, ",", &saveptr
);
3781 tok
= strtok_r (NULL
, ",", &saveptr
))
3783 if (strcmp ("vCont", tok
) == 0)
3784 disable_packet_vCont
= true;
3785 else if (strcmp ("Tthread", tok
) == 0)
3786 disable_packet_Tthread
= true;
3787 else if (strcmp ("qC", tok
) == 0)
3788 disable_packet_qC
= true;
3789 else if (strcmp ("qfThreadInfo", tok
) == 0)
3790 disable_packet_qfThreadInfo
= true;
3791 else if (strcmp ("T", tok
) == 0)
3792 disable_packet_T
= true;
3793 else if (strcmp ("threads", tok
) == 0)
3795 disable_packet_vCont
= true;
3796 disable_packet_Tthread
= true;
3797 disable_packet_qC
= true;
3798 disable_packet_qfThreadInfo
= true;
3802 fprintf (stderr
, "Don't know how to disable \"%s\".\n\n",
3804 gdbserver_show_disableable (stderr
);
3809 else if (strcmp (*next_arg
, "-") == 0)
3811 /* "-" specifies a stdio connection and is a form of port
3813 port
= STDIO_CONNECTION_NAME
;
3817 else if (strcmp (*next_arg
, "--disable-randomization") == 0)
3818 cs
.disable_randomization
= 1;
3819 else if (strcmp (*next_arg
, "--no-disable-randomization") == 0)
3820 cs
.disable_randomization
= 0;
3821 else if (strcmp (*next_arg
, "--startup-with-shell") == 0)
3822 startup_with_shell
= true;
3823 else if (strcmp (*next_arg
, "--no-startup-with-shell") == 0)
3824 startup_with_shell
= false;
3825 else if (strcmp (*next_arg
, "--once") == 0)
3827 else if (strcmp (*next_arg
, "--selftest") == 0)
3829 else if (startswith (*next_arg
, "--selftest="))
3834 const char *filter
= *next_arg
+ strlen ("--selftest=");
3835 if (*filter
== '\0')
3837 fprintf (stderr
, _("Error: selftest filter is empty.\n"));
3841 selftest_filters
.push_back (filter
);
3846 fprintf (stderr
, "Unknown argument: %s\n", *next_arg
);
3859 if ((port
== NULL
|| (!attach
&& !multi_mode
&& *next_arg
== NULL
))
3862 gdbserver_usage (stderr
);
3866 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
3867 opened by remote_prepare. */
3870 save_original_signals_state (false);
3872 /* We need to know whether the remote connection is stdio before
3873 starting the inferior. Inferiors created in this scenario have
3874 stdin,stdout redirected. So do this here before we call
3877 remote_prepare (port
);
3882 /* --attach used to come after PORT, so allow it there for
3884 if (*next_arg
!= NULL
&& strcmp (*next_arg
, "--attach") == 0)
3891 && (*next_arg
== NULL
3892 || (*next_arg
)[0] == '\0'
3893 || (pid
= strtoul (*next_arg
, &arg_end
, 0)) == 0
3895 || next_arg
[1] != NULL
))
3900 gdbserver_usage (stderr
);
3904 /* Gather information about the environment. */
3905 our_environ
= gdb_environ::from_host_environ ();
3907 initialize_async_io ();
3909 have_job_control ();
3910 if (target_supports_tracepoints ())
3911 initialize_tracepoint ();
3913 mem_buf
= (unsigned char *) xmalloc (PBUFSIZ
);
3918 selftests::run_tests (selftest_filters
);
3920 printf (_("Selftests have been disabled for this build.\n"));
3922 throw_quit ("Quit");
3925 if (pid
== 0 && *next_arg
!= NULL
)
3929 n
= argc
- (next_arg
- argv
);
3930 program_path
.set (next_arg
[0]);
3931 for (i
= 1; i
< n
; i
++)
3932 program_args
.push_back (xstrdup (next_arg
[i
]));
3934 /* Wait till we are at first instruction in program. */
3935 target_create_inferior (program_path
.get (), program_args
);
3937 /* We are now (hopefully) stopped at the first instruction of
3938 the target process. This assumes that the target process was
3939 successfully created. */
3943 if (attach_inferior (pid
) == -1)
3944 error ("Attaching not supported on this target");
3946 /* Otherwise succeeded. */
3950 cs
.last_status
.set_exited (0);
3951 cs
.last_ptid
= minus_one_ptid
;
3954 SCOPE_EXIT
{ detach_or_kill_for_exit_cleanup (); };
3956 /* Don't report shared library events on the initial connection,
3957 even if some libraries are preloaded. Avoids the "stopped by
3958 shared library event" notice on gdb side. */
3959 if (current_thread
!= nullptr)
3960 current_process ()->dlls_changed
= false;
3962 if (cs
.last_status
.kind () == TARGET_WAITKIND_EXITED
3963 || cs
.last_status
.kind () == TARGET_WAITKIND_SIGNALLED
)
3968 if (!was_running
&& !multi_mode
)
3969 error ("No program to debug");
3974 cs
.multi_process
= 0;
3975 cs
.report_fork_events
= 0;
3976 cs
.report_vfork_events
= 0;
3977 cs
.report_exec_events
= 0;
3978 /* Be sure we're out of tfind mode. */
3979 cs
.current_traceframe
= -1;
3980 cs
.cont_thread
= null_ptid
;
3981 cs
.swbreak_feature
= 0;
3982 cs
.hwbreak_feature
= 0;
3983 cs
.vCont_supported
= 0;
3984 cs
.memory_tagging_feature
= false;
3990 /* Wait for events. This will return when all event sources
3991 are removed from the event loop. */
3992 start_event_loop ();
3994 /* If an exit was requested (using the "monitor exit"
3995 command), terminate now. */
3997 throw_quit ("Quit");
3999 /* The only other way to get here is for getpkt to fail:
4001 - If --once was specified, we're done.
4003 - If not in extended-remote mode, and we're no longer
4004 debugging anything, simply exit: GDB has disconnected
4005 after processing the last process exit.
4007 - Otherwise, close the connection and reopen it at the
4009 if (run_once
|| (!extended_protocol
&& !target_running ()))
4010 throw_quit ("Quit");
4013 "Remote side has terminated connection. "
4014 "GDBserver will reopen the connection.\n");
4016 /* Get rid of any pending statuses. An eventual reconnection
4017 (by the same GDB instance or another) will refresh all its
4018 state from scratch. */
4019 discard_queued_stop_replies (minus_one_ptid
);
4020 for_each_thread ([] (thread_info
*thread
)
4022 thread
->status_pending_p
= 0;
4027 if (disconnected_tracing
)
4029 /* Try to enable non-stop/async mode, so we we can
4030 both wait for an async socket accept, and handle
4031 async target events simultaneously. There's also
4032 no point either in having the target always stop
4033 all threads, when we're going to pass signals
4034 down without informing GDB. */
4037 if (the_target
->start_non_stop (true))
4040 /* Detaching implicitly resumes all threads;
4041 simply disconnecting does not. */
4047 "Disconnected tracing disabled; "
4048 "stopping trace run.\n");
4053 catch (const gdb_exception_error
&exception
)
4056 fprintf (stderr
, "gdbserver: %s\n", exception
.what ());
4058 if (response_needed
)
4060 write_enn (cs
.own_buf
);
4061 putpkt (cs
.own_buf
);
4065 throw_quit ("Quit");
4070 /* Main function. */
4073 main (int argc
, char *argv
[])
4078 captured_main (argc
, argv
);
4080 catch (const gdb_exception
&exception
)
4082 if (exception
.reason
== RETURN_ERROR
)
4085 fprintf (stderr
, "%s\n", exception
.what ());
4086 fprintf (stderr
, "Exiting\n");
4093 gdb_assert_not_reached ("captured_main should never return");
4096 /* Process options coming from Z packets for a breakpoint. PACKET is
4097 the packet buffer. *PACKET is updated to point to the first char
4098 after the last processed option. */
4101 process_point_options (struct gdb_breakpoint
*bp
, const char **packet
)
4103 const char *dataptr
= *packet
;
4106 /* Check if data has the correct format. */
4107 if (*dataptr
!= ';')
4114 if (*dataptr
== ';')
4117 if (*dataptr
== 'X')
4119 /* Conditional expression. */
4120 threads_debug_printf ("Found breakpoint condition.");
4121 if (!add_breakpoint_condition (bp
, &dataptr
))
4122 dataptr
= strchrnul (dataptr
, ';');
4124 else if (startswith (dataptr
, "cmds:"))
4126 dataptr
+= strlen ("cmds:");
4127 threads_debug_printf ("Found breakpoint commands %s.", dataptr
);
4128 persist
= (*dataptr
== '1');
4130 if (add_breakpoint_commands (bp
, &dataptr
, persist
))
4131 dataptr
= strchrnul (dataptr
, ';');
4135 fprintf (stderr
, "Unknown token %c, ignoring.\n",
4137 /* Skip tokens until we find one that we recognize. */
4138 dataptr
= strchrnul (dataptr
, ';');
4144 /* Event loop callback that handles a serial event. The first byte in
4145 the serial buffer gets us here. We expect characters to arrive at
4146 a brisk pace, so we read the rest of the packet with a blocking
4150 process_serial_event (void)
4152 client_state
&cs
= get_client_state ();
4158 int new_packet_len
= -1;
4160 disable_async_io ();
4162 response_needed
= false;
4163 packet_len
= getpkt (cs
.own_buf
);
4164 if (packet_len
<= 0)
4167 /* Force an event loop break. */
4170 response_needed
= true;
4172 char ch
= cs
.own_buf
[0];
4176 handle_query (cs
.own_buf
, packet_len
, &new_packet_len
);
4179 handle_general_set (cs
.own_buf
);
4182 handle_detach (cs
.own_buf
);
4185 extended_protocol
= true;
4186 write_ok (cs
.own_buf
);
4189 handle_status (cs
.own_buf
);
4192 if (cs
.own_buf
[1] == 'c' || cs
.own_buf
[1] == 'g' || cs
.own_buf
[1] == 's')
4194 require_running_or_break (cs
.own_buf
);
4196 ptid_t thread_id
= read_ptid (&cs
.own_buf
[2], NULL
);
4198 if (thread_id
== null_ptid
|| thread_id
== minus_one_ptid
)
4199 thread_id
= null_ptid
;
4200 else if (thread_id
.is_pid ())
4202 /* The ptid represents a pid. */
4203 thread_info
*thread
= find_any_thread_of_pid (thread_id
.pid ());
4207 write_enn (cs
.own_buf
);
4211 thread_id
= thread
->id
;
4215 /* The ptid represents a lwp/tid. */
4216 if (find_thread_ptid (thread_id
) == NULL
)
4218 write_enn (cs
.own_buf
);
4223 if (cs
.own_buf
[1] == 'g')
4225 if (thread_id
== null_ptid
)
4227 /* GDB is telling us to choose any thread. Check if
4228 the currently selected thread is still valid. If
4229 it is not, select the first available. */
4230 thread_info
*thread
= find_thread_ptid (cs
.general_thread
);
4232 thread
= get_first_thread ();
4233 thread_id
= thread
->id
;
4236 cs
.general_thread
= thread_id
;
4237 set_desired_thread ();
4238 gdb_assert (current_thread
!= NULL
);
4240 else if (cs
.own_buf
[1] == 'c')
4241 cs
.cont_thread
= thread_id
;
4243 write_ok (cs
.own_buf
);
4247 /* Silently ignore it so that gdb can extend the protocol
4248 without compatibility headaches. */
4249 cs
.own_buf
[0] = '\0';
4253 require_running_or_break (cs
.own_buf
);
4254 if (cs
.current_traceframe
>= 0)
4256 struct regcache
*regcache
4257 = new_register_cache (current_target_desc ());
4259 if (fetch_traceframe_registers (cs
.current_traceframe
,
4261 registers_to_string (regcache
, cs
.own_buf
);
4263 write_enn (cs
.own_buf
);
4264 free_register_cache (regcache
);
4268 struct regcache
*regcache
;
4270 if (!set_desired_thread ())
4271 write_enn (cs
.own_buf
);
4274 regcache
= get_thread_regcache (current_thread
, 1);
4275 registers_to_string (regcache
, cs
.own_buf
);
4280 require_running_or_break (cs
.own_buf
);
4281 if (cs
.current_traceframe
>= 0)
4282 write_enn (cs
.own_buf
);
4285 struct regcache
*regcache
;
4287 if (!set_desired_thread ())
4288 write_enn (cs
.own_buf
);
4291 regcache
= get_thread_regcache (current_thread
, 1);
4292 registers_from_string (regcache
, &cs
.own_buf
[1]);
4293 write_ok (cs
.own_buf
);
4299 require_running_or_break (cs
.own_buf
);
4300 decode_m_packet (&cs
.own_buf
[1], &mem_addr
, &len
);
4301 int res
= gdb_read_memory (mem_addr
, mem_buf
, len
);
4303 write_enn (cs
.own_buf
);
4305 bin2hex (mem_buf
, cs
.own_buf
, res
);
4309 require_running_or_break (cs
.own_buf
);
4310 decode_M_packet (&cs
.own_buf
[1], &mem_addr
, &len
, &mem_buf
);
4311 if (gdb_write_memory (mem_addr
, mem_buf
, len
) == 0)
4312 write_ok (cs
.own_buf
);
4314 write_enn (cs
.own_buf
);
4317 require_running_or_break (cs
.own_buf
);
4318 if (decode_X_packet (&cs
.own_buf
[1], packet_len
- 1,
4319 &mem_addr
, &len
, &mem_buf
) < 0
4320 || gdb_write_memory (mem_addr
, mem_buf
, len
) != 0)
4321 write_enn (cs
.own_buf
);
4323 write_ok (cs
.own_buf
);
4326 require_running_or_break (cs
.own_buf
);
4327 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4328 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4329 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4332 myresume (cs
.own_buf
, 0, signal
);
4335 require_running_or_break (cs
.own_buf
);
4336 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4337 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4338 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4341 myresume (cs
.own_buf
, 1, signal
);
4344 require_running_or_break (cs
.own_buf
);
4346 myresume (cs
.own_buf
, 0, signal
);
4349 require_running_or_break (cs
.own_buf
);
4351 myresume (cs
.own_buf
, 1, signal
);
4353 case 'Z': /* insert_ ... */
4355 case 'z': /* remove_ ... */
4360 char type
= cs
.own_buf
[1];
4362 const int insert
= ch
== 'Z';
4363 const char *p
= &cs
.own_buf
[3];
4365 p
= unpack_varlen_hex (p
, &addr
);
4366 kind
= strtol (p
+ 1, &dataptr
, 16);
4370 struct gdb_breakpoint
*bp
;
4372 bp
= set_gdb_breakpoint (type
, addr
, kind
, &res
);
4377 /* GDB may have sent us a list of *point parameters to
4378 be evaluated on the target's side. Read such list
4379 here. If we already have a list of parameters, GDB
4380 is telling us to drop that list and use this one
4382 clear_breakpoint_conditions_and_commands (bp
);
4383 const char *options
= dataptr
;
4384 process_point_options (bp
, &options
);
4388 res
= delete_gdb_breakpoint (type
, addr
, kind
);
4391 write_ok (cs
.own_buf
);
4394 cs
.own_buf
[0] = '\0';
4396 write_enn (cs
.own_buf
);
4400 response_needed
= false;
4401 if (!target_running ())
4402 /* The packet we received doesn't make sense - but we can't
4403 reply to it, either. */
4406 fprintf (stderr
, "Killing all inferiors\n");
4408 for_each_process (kill_inferior_callback
);
4410 /* When using the extended protocol, we wait with no program
4411 running. The traditional protocol will exit instead. */
4412 if (extended_protocol
)
4414 cs
.last_status
.set_exited (GDB_SIGNAL_KILL
);
4422 require_running_or_break (cs
.own_buf
);
4424 ptid_t thread_id
= read_ptid (&cs
.own_buf
[1], NULL
);
4425 if (find_thread_ptid (thread_id
) == NULL
)
4427 write_enn (cs
.own_buf
);
4431 if (mythread_alive (thread_id
))
4432 write_ok (cs
.own_buf
);
4434 write_enn (cs
.own_buf
);
4438 response_needed
= false;
4440 /* Restarting the inferior is only supported in the extended
4442 if (extended_protocol
)
4444 if (target_running ())
4445 for_each_process (kill_inferior_callback
);
4447 fprintf (stderr
, "GDBserver restarting\n");
4449 /* Wait till we are at 1st instruction in prog. */
4450 if (program_path
.get () != NULL
)
4452 target_create_inferior (program_path
.get (), program_args
);
4454 if (cs
.last_status
.kind () == TARGET_WAITKIND_STOPPED
)
4456 /* Stopped at the first instruction of the target
4458 cs
.general_thread
= cs
.last_ptid
;
4462 /* Something went wrong. */
4463 cs
.general_thread
= null_ptid
;
4468 cs
.last_status
.set_exited (GDB_SIGNAL_KILL
);
4474 /* It is a request we don't understand. Respond with an
4475 empty packet so that gdb knows that we don't support this
4477 cs
.own_buf
[0] = '\0';
4481 /* Extended (long) request. */
4482 handle_v_requests (cs
.own_buf
, packet_len
, &new_packet_len
);
4486 /* It is a request we don't understand. Respond with an empty
4487 packet so that gdb knows that we don't support this
4489 cs
.own_buf
[0] = '\0';
4493 if (new_packet_len
!= -1)
4494 putpkt_binary (cs
.own_buf
, new_packet_len
);
4496 putpkt (cs
.own_buf
);
4498 response_needed
= false;
4506 /* Event-loop callback for serial events. */
4509 handle_serial_event (int err
, gdb_client_data client_data
)
4511 threads_debug_printf ("handling possible serial event");
4513 /* Really handle it. */
4514 if (process_serial_event () < 0)
4516 keep_processing_events
= false;
4520 /* Be sure to not change the selected thread behind GDB's back.
4521 Important in the non-stop mode asynchronous protocol. */
4522 set_desired_thread ();
4525 /* Push a stop notification on the notification queue. */
4528 push_stop_notification (ptid_t ptid
, const target_waitstatus
&status
)
4530 struct vstop_notif
*vstop_notif
= new struct vstop_notif
;
4532 vstop_notif
->status
= status
;
4533 vstop_notif
->ptid
= ptid
;
4534 /* Push Stop notification. */
4535 notif_push (¬if_stop
, vstop_notif
);
4538 /* Event-loop callback for target events. */
4541 handle_target_event (int err
, gdb_client_data client_data
)
4543 client_state
&cs
= get_client_state ();
4544 threads_debug_printf ("handling possible target event");
4546 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
,
4549 if (cs
.last_status
.kind () == TARGET_WAITKIND_NO_RESUMED
)
4551 if (gdb_connected () && report_no_resumed
)
4552 push_stop_notification (null_ptid
, cs
.last_status
);
4554 else if (cs
.last_status
.kind () != TARGET_WAITKIND_IGNORE
)
4556 int pid
= cs
.last_ptid
.pid ();
4557 struct process_info
*process
= find_process_pid (pid
);
4558 int forward_event
= !gdb_connected () || process
->gdb_detached
;
4560 if (cs
.last_status
.kind () == TARGET_WAITKIND_EXITED
4561 || cs
.last_status
.kind () == TARGET_WAITKIND_SIGNALLED
)
4563 mark_breakpoints_out (process
);
4564 target_mourn_inferior (cs
.last_ptid
);
4566 else if (cs
.last_status
.kind () == TARGET_WAITKIND_THREAD_EXITED
)
4570 /* We're reporting this thread as stopped. Update its
4571 "want-stopped" state to what the client wants, until it
4572 gets a new resume action. */
4573 current_thread
->last_resume_kind
= resume_stop
;
4574 current_thread
->last_status
= cs
.last_status
;
4579 if (!target_running ())
4581 /* The last process exited. We're done. */
4585 if (cs
.last_status
.kind () == TARGET_WAITKIND_EXITED
4586 || cs
.last_status
.kind () == TARGET_WAITKIND_SIGNALLED
4587 || cs
.last_status
.kind () == TARGET_WAITKIND_THREAD_EXITED
)
4591 /* A thread stopped with a signal, but gdb isn't
4592 connected to handle it. Pass it down to the
4593 inferior, as if it wasn't being traced. */
4594 enum gdb_signal signal
;
4596 threads_debug_printf ("GDB not connected; forwarding event %d for"
4598 (int) cs
.last_status
.kind (),
4599 target_pid_to_str (cs
.last_ptid
).c_str ());
4601 if (cs
.last_status
.kind () == TARGET_WAITKIND_STOPPED
)
4602 signal
= cs
.last_status
.sig ();
4604 signal
= GDB_SIGNAL_0
;
4605 target_continue (cs
.last_ptid
, signal
);
4609 push_stop_notification (cs
.last_ptid
, cs
.last_status
);
4612 /* Be sure to not change the selected thread behind GDB's back.
4613 Important in the non-stop mode asynchronous protocol. */
4614 set_desired_thread ();
4617 /* See gdbsupport/event-loop.h. */
4620 invoke_async_signal_handlers ()
4625 /* See gdbsupport/event-loop.h. */
4628 check_async_event_handlers ()
4633 /* See gdbsupport/errors.h */
4642 /* See gdbsupport/gdb_select.h. */
4645 gdb_select (int n
, fd_set
*readfds
, fd_set
*writefds
,
4646 fd_set
*exceptfds
, struct timeval
*timeout
)
4648 return select (n
, readfds
, writefds
, exceptfds
, timeout
);
4659 } // namespace selftests
4660 #endif /* GDB_SELF_TEST */