1 /* Main code for remote server for GDB.
2 Copyright (C) 1989-2024 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/>. */
19 #include "gdbthread.h"
20 #include "gdbsupport/agent.h"
23 #include "gdbsupport/rsp-low.h"
24 #include "gdbsupport/signals-state-save-restore.h"
30 #include "gdbsupport/gdb_vecs.h"
31 #include "gdbsupport/gdb_wait.h"
32 #include "gdbsupport/btrace-common.h"
33 #include "gdbsupport/filestuff.h"
34 #include "tracepoint.h"
38 #include <unordered_map>
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"
53 #include "gdbsupport/gdb_argv_vec.h"
55 /* PBUFSIZ must also be at least as big as IPA_CMD_BUF_SIZE, because
56 the client state data is passed directly to some agent
58 static_assert (PBUFSIZ
>= IPA_CMD_BUF_SIZE
);
60 #define require_running_or_return(BUF) \
61 if (!target_running ()) \
67 #define require_running_or_break(BUF) \
68 if (!target_running ()) \
74 /* The environment to pass to the inferior when creating it. */
76 static gdb_environ our_environ
;
80 static bool extended_protocol
;
81 static bool response_needed
;
82 static bool exit_requested
;
84 /* --once: Exit after the first connection has closed. */
87 /* Whether to report TARGET_WAITKIND_NO_RESUMED events. */
88 static bool report_no_resumed
;
90 /* The event loop checks this to decide whether to continue accepting
92 static bool keep_processing_events
= true;
97 /* Set the PROGRAM_PATH. Here we adjust the path of the provided
99 void set (const char *path
)
103 /* Make sure we're using the absolute path of the inferior when
105 if (!contains_dir_separator (m_path
.c_str ()))
109 /* Check if the file is in our CWD. If it is, then we prefix
110 its name with CURRENT_DIRECTORY. Otherwise, we leave the
111 name as-is because we'll try searching for it in $PATH. */
112 if (is_regular_file (m_path
.c_str (), ®_file_errno
))
113 m_path
= gdb_abspath (m_path
);
117 /* Return the PROGRAM_PATH. */
119 { return m_path
.empty () ? nullptr : m_path
.c_str (); }
122 /* The program name, adjusted if needed. */
126 /* All program arguments are merged into a single string. */
128 static std::string program_args
;
130 static std::string wrapper_argv
;
132 /* The PID of the originally created or attached inferior. Used to
133 send signals to the process when GDB sends us an asynchronous interrupt
134 (user hitting Control-C in the client), and to wait for the child to exit
135 when no longer debugging it. */
137 unsigned long signal_pid
;
139 /* Set if you want to disable optional thread related packets support
140 in gdbserver, for the sake of testing GDB against stubs that don't
142 bool disable_packet_vCont
;
143 bool disable_packet_Tthread
;
144 bool disable_packet_qC
;
145 bool disable_packet_qfThreadInfo
;
146 bool disable_packet_T
;
148 static unsigned char *mem_buf
;
150 /* A sub-class of 'struct notif_event' for stop, holding information
151 relative to a single stop reply. We keep a queue of these to
152 push to GDB in non-stop mode. */
154 struct vstop_notif
: public notif_event
156 /* Thread or process that got the event. */
160 struct target_waitstatus status
;
163 /* The current btrace configuration. This is gdbserver's mirror of GDB's
164 btrace configuration. */
165 static struct btrace_config current_btrace_conf
;
167 /* The client remote protocol state. */
169 static client_state g_client_state
;
174 client_state
&cs
= g_client_state
;
179 /* Put a stop reply to the stop reply queue. */
182 queue_stop_reply (ptid_t ptid
, const target_waitstatus
&status
)
184 struct vstop_notif
*new_notif
= new struct vstop_notif
;
186 new_notif
->ptid
= ptid
;
187 new_notif
->status
= status
;
189 notif_event_enque (¬if_stop
, new_notif
);
193 remove_all_on_match_ptid (struct notif_event
*event
, ptid_t filter_ptid
)
195 struct vstop_notif
*vstop_event
= (struct vstop_notif
*) event
;
197 return vstop_event
->ptid
.matches (filter_ptid
);
203 discard_queued_stop_replies (ptid_t ptid
)
205 std::list
<notif_event
*>::iterator iter
, next
, end
;
206 end
= notif_stop
.queue
.end ();
207 for (iter
= notif_stop
.queue
.begin (); iter
!= end
; iter
= next
)
212 if (iter
== notif_stop
.queue
.begin ())
214 /* The head of the list contains the notification that was
215 already sent to GDB. So we can't remove it, otherwise
216 when GDB sends the vStopped, it would ack the _next_
217 notification, which hadn't been sent yet! */
221 if (remove_all_on_match_ptid (*iter
, ptid
))
224 notif_stop
.queue
.erase (iter
);
230 vstop_notif_reply (struct notif_event
*event
, char *own_buf
)
232 struct vstop_notif
*vstop
= (struct vstop_notif
*) event
;
234 prepare_resume_reply (own_buf
, vstop
->ptid
, vstop
->status
);
237 /* Helper for in_queued_stop_replies. */
240 in_queued_stop_replies_ptid (struct notif_event
*event
, ptid_t filter_ptid
)
242 struct vstop_notif
*vstop_event
= (struct vstop_notif
*) event
;
244 if (vstop_event
->ptid
.matches (filter_ptid
))
247 /* Don't resume fork children that GDB does not know about yet. */
248 if ((vstop_event
->status
.kind () == TARGET_WAITKIND_FORKED
249 || vstop_event
->status
.kind () == TARGET_WAITKIND_VFORKED
250 || vstop_event
->status
.kind () == TARGET_WAITKIND_THREAD_CLONED
)
251 && vstop_event
->status
.child_ptid ().matches (filter_ptid
))
260 in_queued_stop_replies (ptid_t ptid
)
262 for (notif_event
*event
: notif_stop
.queue
)
264 if (in_queued_stop_replies_ptid (event
, ptid
))
271 struct notif_server notif_stop
=
273 "vStopped", "Stop", {}, vstop_notif_reply
,
277 target_running (void)
279 return get_first_thread () != NULL
;
282 /* See gdbsupport/common-inferior.h. */
287 return !wrapper_argv
.empty () ? wrapper_argv
.c_str () : NULL
;
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 (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 (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 (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 ();
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 ();
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
;
545 else if (strncmp (op
, "pt:ptwrite=", strlen ("pt:ptwrite=")) == 0)
547 op
+= strlen ("pt:ptwrite=");
548 if (strncmp (op
, "\"yes\"", strlen ("\"yes\"")) == 0)
549 current_btrace_conf
.pt
.ptwrite
= true;
550 else if (strncmp (op
, "\"no\"", strlen ("\"no\"")) == 0)
551 current_btrace_conf
.pt
.ptwrite
= false;
554 strcpy (own_buf
, "E.Bad ptwrite value.");
558 else if (strncmp (op
, "pt:event-tracing=", strlen ("pt:event-tracing=")) == 0)
560 op
+= strlen ("pt:event-tracing=");
561 if (strncmp (op
, "\"yes\"", strlen ("\"yes\"")) == 0)
562 current_btrace_conf
.pt
.event_tracing
= true;
563 else if (strncmp (op
, "\"no\"", strlen ("\"no\"")) == 0)
564 current_btrace_conf
.pt
.event_tracing
= false;
567 strcpy (own_buf
, "E.Bad event-tracing value.");
573 strcpy (own_buf
, "E.Bad Qbtrace configuration option.");
581 /* Create the qMemTags packet reply given TAGS.
583 Returns true if parsing succeeded and false otherwise. */
586 create_fetch_memtags_reply (char *reply
, const gdb::byte_vector
&tags
)
588 /* It is an error to pass a zero-sized tag vector. */
589 gdb_assert (tags
.size () != 0);
591 std::string
packet ("m");
593 /* Write the tag data. */
594 packet
+= bin2hex (tags
.data (), tags
.size ());
596 /* Check if the reply is too big for the packet to handle. */
597 if (PBUFSIZ
< packet
.size ())
600 strcpy (reply
, packet
.c_str ());
604 /* Parse the QMemTags request into ADDR, LEN and TAGS.
606 Returns true if parsing succeeded and false otherwise. */
609 parse_store_memtags_request (char *request
, CORE_ADDR
*addr
, size_t *len
,
610 gdb::byte_vector
&tags
, int *type
)
612 gdb_assert (startswith (request
, "QMemTags:"));
614 const char *p
= request
+ strlen ("QMemTags:");
616 /* Read address and length. */
617 unsigned int length
= 0;
618 p
= decode_m_packet_params (p
, addr
, &length
, ':');
621 /* Read the tag type. */
622 ULONGEST tag_type
= 0;
623 p
= unpack_varlen_hex (p
, &tag_type
);
624 *type
= (int) tag_type
;
626 /* Make sure there is a colon after the type. */
630 /* Skip the colon. */
633 /* Read the tag data. */
639 /* Parse thread options starting at *P and return them. On exit,
640 advance *P past the options. */
642 static gdb_thread_options
643 parse_gdb_thread_options (const char **p
)
645 ULONGEST options
= 0;
646 *p
= unpack_varlen_hex (*p
, &options
);
647 return (gdb_thread_option
) options
;
650 /* Handle all of the extended 'Q' packets. */
653 handle_general_set (char *own_buf
)
655 client_state
&cs
= get_client_state ();
656 if (startswith (own_buf
, "QPassSignals:"))
658 int numsigs
= (int) GDB_SIGNAL_LAST
, i
;
659 const char *p
= own_buf
+ strlen ("QPassSignals:");
662 p
= decode_address_to_semicolon (&cursig
, p
);
663 for (i
= 0; i
< numsigs
; i
++)
667 cs
.pass_signals
[i
] = 1;
669 /* Keep looping, to clear the remaining signals. */
672 p
= decode_address_to_semicolon (&cursig
, p
);
675 cs
.pass_signals
[i
] = 0;
677 strcpy (own_buf
, "OK");
681 if (startswith (own_buf
, "QProgramSignals:"))
683 int numsigs
= (int) GDB_SIGNAL_LAST
, i
;
684 const char *p
= own_buf
+ strlen ("QProgramSignals:");
687 cs
.program_signals_p
= 1;
689 p
= decode_address_to_semicolon (&cursig
, p
);
690 for (i
= 0; i
< numsigs
; i
++)
694 cs
.program_signals
[i
] = 1;
696 /* Keep looping, to clear the remaining signals. */
699 p
= decode_address_to_semicolon (&cursig
, p
);
702 cs
.program_signals
[i
] = 0;
704 strcpy (own_buf
, "OK");
708 if (startswith (own_buf
, "QCatchSyscalls:"))
710 const char *p
= own_buf
+ sizeof ("QCatchSyscalls:") - 1;
713 struct process_info
*process
;
715 if (!target_running () || !target_supports_catch_syscall ())
721 if (strcmp (p
, "0") == 0)
723 else if (p
[0] == '1' && (p
[1] == ';' || p
[1] == '\0'))
727 fprintf (stderr
, "Unknown catch-syscalls mode requested: %s\n",
733 process
= current_process ();
734 process
->syscalls_to_catch
.clear ();
744 p
= decode_address_to_semicolon (&sysno
, p
);
745 process
->syscalls_to_catch
.push_back (sysno
);
749 process
->syscalls_to_catch
.push_back (ANY_SYSCALL
);
756 if (strcmp (own_buf
, "QEnvironmentReset") == 0)
758 our_environ
= gdb_environ::from_host_environ ();
764 if (startswith (own_buf
, "QEnvironmentHexEncoded:"))
766 const char *p
= own_buf
+ sizeof ("QEnvironmentHexEncoded:") - 1;
767 /* The final form of the environment variable. FINAL_VAR will
768 hold the 'VAR=VALUE' format. */
769 std::string final_var
= hex2str (p
);
770 std::string var_name
, var_value
;
772 remote_debug_printf ("[QEnvironmentHexEncoded received '%s']", p
);
773 remote_debug_printf ("[Environment variable to be set: '%s']",
776 size_t pos
= final_var
.find ('=');
777 if (pos
== std::string::npos
)
779 warning (_("Unexpected format for environment variable: '%s'"),
785 var_name
= final_var
.substr (0, pos
);
786 var_value
= final_var
.substr (pos
+ 1, std::string::npos
);
788 our_environ
.set (var_name
.c_str (), var_value
.c_str ());
794 if (startswith (own_buf
, "QEnvironmentUnset:"))
796 const char *p
= own_buf
+ sizeof ("QEnvironmentUnset:") - 1;
797 std::string varname
= hex2str (p
);
799 remote_debug_printf ("[QEnvironmentUnset received '%s']", p
);
800 remote_debug_printf ("[Environment variable to be unset: '%s']",
803 our_environ
.unset (varname
.c_str ());
809 if (strcmp (own_buf
, "QStartNoAckMode") == 0)
811 remote_debug_printf ("[noack mode enabled]");
818 if (startswith (own_buf
, "QNonStop:"))
820 char *mode
= own_buf
+ 9;
824 if (strcmp (mode
, "0") == 0)
826 else if (strcmp (mode
, "1") == 0)
830 /* We don't know what this mode is, so complain to
832 fprintf (stderr
, "Unknown non-stop mode requested: %s\n",
838 req_str
= req
? "non-stop" : "all-stop";
839 if (the_target
->start_non_stop (req
== 1) != 0)
841 fprintf (stderr
, "Setting %s mode failed\n", req_str
);
846 non_stop
= (req
!= 0);
848 remote_debug_printf ("[%s mode enabled]", req_str
);
854 if (startswith (own_buf
, "QDisableRandomization:"))
856 char *packet
= own_buf
+ strlen ("QDisableRandomization:");
859 unpack_varlen_hex (packet
, &setting
);
860 cs
.disable_randomization
= setting
;
862 remote_debug_printf (cs
.disable_randomization
863 ? "[address space randomization disabled]"
864 : "[address space randomization enabled]");
870 if (target_supports_tracepoints ()
871 && handle_tracepoint_general_set (own_buf
))
874 if (startswith (own_buf
, "QAgent:"))
876 char *mode
= own_buf
+ strlen ("QAgent:");
879 if (strcmp (mode
, "0") == 0)
881 else if (strcmp (mode
, "1") == 0)
885 /* We don't know what this value is, so complain to GDB. */
886 sprintf (own_buf
, "E.Unknown QAgent value");
890 /* Update the flag. */
892 remote_debug_printf ("[%s agent]", req
? "Enable" : "Disable");
897 if (handle_btrace_general_set (own_buf
))
900 if (handle_btrace_conf_general_set (own_buf
))
903 if (startswith (own_buf
, "QThreadEvents:"))
905 char *mode
= own_buf
+ strlen ("QThreadEvents:");
906 enum tribool req
= TRIBOOL_UNKNOWN
;
908 if (strcmp (mode
, "0") == 0)
910 else if (strcmp (mode
, "1") == 0)
914 /* We don't know what this mode is, so complain to GDB. */
916 = string_printf ("E.Unknown thread-events mode requested: %s\n",
918 strcpy (own_buf
, err
.c_str ());
922 cs
.report_thread_events
= (req
== TRIBOOL_TRUE
);
924 remote_debug_printf ("[thread events are now %s]\n",
925 cs
.report_thread_events
? "enabled" : "disabled");
931 if (startswith (own_buf
, "QThreadOptions;"))
933 const char *p
= own_buf
+ strlen ("QThreadOptions");
935 gdb_thread_options supported_options
= target_supported_thread_options ();
936 if (supported_options
== 0)
938 /* Something went wrong -- we don't support any option, but
939 GDB sent the packet anyway. */
944 /* We could store the options directly in thread->thread_options
945 without this map, but that would mean that a QThreadOptions
946 packet with a wildcard like "QThreadOptions;0;3:TID" would
947 result in the debug logs showing:
949 [options for TID are now 0x0]
950 [options for TID are now 0x3]
952 It's nicer if we only print the final options for each TID,
953 and if we only print about it if the options changed compared
954 to the options that were previously set on the thread. */
955 std::unordered_map
<thread_info
*, gdb_thread_options
> set_options
;
966 /* Read the options. */
968 gdb_thread_options options
= parse_gdb_thread_options (&p
);
970 if ((options
& ~supported_options
) != 0)
972 /* GDB asked for an unknown or unsupported option, so
975 = string_printf ("E.Unknown thread options requested: %s\n",
976 to_string (options
).c_str ());
977 strcpy (own_buf
, err
.c_str ());
983 if (p
[0] == ';' || p
[0] == '\0')
984 ptid
= minus_one_ptid
;
985 else if (p
[0] == ':')
989 ptid
= read_ptid (p
+ 1, &q
);
997 if (p
[0] != ';' && p
[0] != '\0')
1005 write_enn (own_buf
);
1009 /* Convert PID.-1 => PID.0 for ptid.matches. */
1010 if (ptid
.lwp () == -1)
1011 ptid
= ptid_t (ptid
.pid ());
1013 for_each_thread ([&] (thread_info
*thread
)
1015 if (thread
->id
.matches (ptid
))
1016 set_options
[thread
] = options
;
1020 for (const auto &iter
: set_options
)
1022 thread_info
*thread
= iter
.first
;
1023 gdb_thread_options options
= iter
.second
;
1025 if (thread
->thread_options
!= options
)
1027 threads_debug_printf ("[options for %s are now %s]\n",
1028 target_pid_to_str (thread
->id
).c_str (),
1029 to_string (options
).c_str ());
1031 thread
->thread_options
= options
;
1039 if (startswith (own_buf
, "QStartupWithShell:"))
1041 const char *value
= own_buf
+ strlen ("QStartupWithShell:");
1043 if (strcmp (value
, "1") == 0)
1044 startup_with_shell
= true;
1045 else if (strcmp (value
, "0") == 0)
1046 startup_with_shell
= false;
1049 /* Unknown value. */
1050 fprintf (stderr
, "Unknown value to startup-with-shell: %s\n",
1052 write_enn (own_buf
);
1056 remote_debug_printf ("[Inferior will %s started with shell]",
1057 startup_with_shell
? "be" : "not be");
1063 if (startswith (own_buf
, "QSetWorkingDir:"))
1065 const char *p
= own_buf
+ strlen ("QSetWorkingDir:");
1069 std::string path
= hex2str (p
);
1071 remote_debug_printf ("[Set the inferior's current directory to %s]",
1074 set_inferior_cwd (std::move (path
));
1078 /* An empty argument means that we should clear out any
1079 previously set cwd for the inferior. */
1080 set_inferior_cwd ("");
1082 remote_debug_printf ("[Unset the inferior's current directory; will "
1083 "use gdbserver's cwd]");
1091 /* Handle store memory tags packets. */
1092 if (startswith (own_buf
, "QMemTags:")
1093 && target_supports_memory_tagging ())
1095 gdb::byte_vector tags
;
1100 require_running_or_return (own_buf
);
1102 bool ret
= parse_store_memtags_request (own_buf
, &addr
, &len
, tags
,
1106 ret
= the_target
->store_memtags (addr
, len
, tags
, type
);
1109 write_enn (own_buf
);
1116 /* Otherwise we didn't know what packet it was. Say we didn't
1122 get_features_xml (const char *annex
)
1124 const struct target_desc
*desc
= current_target_desc ();
1126 /* `desc->xmltarget' defines what to return when looking for the
1127 "target.xml" file. Its contents can either be verbatim XML code
1128 (prefixed with a '@') or else the name of the actual XML file to
1129 be used in place of "target.xml".
1131 This variable is set up from the auto-generated
1132 init_registers_... routine for the current target. */
1134 if (strcmp (annex
, "target.xml") == 0)
1136 const char *ret
= tdesc_get_features_xml (desc
);
1148 /* Look for the annex. */
1149 for (i
= 0; xml_builtin
[i
][0] != NULL
; i
++)
1150 if (strcmp (annex
, xml_builtin
[i
][0]) == 0)
1153 if (xml_builtin
[i
][0] != NULL
)
1154 return xml_builtin
[i
][1];
1162 monitor_show_help (void)
1164 monitor_output ("The following monitor commands are supported:\n");
1165 monitor_output (" set debug on\n");
1166 monitor_output (" Enable general debugging messages\n");
1167 monitor_output (" set debug off\n");
1168 monitor_output (" Disable all debugging messages\n");
1169 monitor_output (" set debug COMPONENT <off|on>\n");
1170 monitor_output (" Enable debugging messages for COMPONENT, which is\n");
1171 monitor_output (" one of: all, threads, remote, event-loop.\n");
1172 monitor_output (" set debug-hw-points <0|1>\n");
1173 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
1174 monitor_output (" set debug-format option1[,option2,...]\n");
1175 monitor_output (" Add additional information to debugging messages\n");
1176 monitor_output (" Options: all, none, timestamp\n");
1177 monitor_output (" exit\n");
1178 monitor_output (" Quit GDBserver\n");
1181 /* Read trace frame or inferior memory. Returns the number of bytes
1182 actually read, zero when no further transfer is possible, and -1 on
1183 error. Return of a positive value smaller than LEN does not
1184 indicate there's no more to be read, only the end of the transfer.
1185 E.g., when GDB reads memory from a traceframe, a first request may
1186 be served from a memory block that does not cover the whole request
1187 length. A following request gets the rest served from either
1188 another block (of the same traceframe) or from the read-only
1192 gdb_read_memory (CORE_ADDR memaddr
, unsigned char *myaddr
, int len
)
1194 client_state
&cs
= get_client_state ();
1197 if (cs
.current_traceframe
>= 0)
1200 ULONGEST length
= len
;
1202 if (traceframe_read_mem (cs
.current_traceframe
,
1203 memaddr
, myaddr
, len
, &nbytes
))
1205 /* Data read from trace buffer, we're done. */
1208 if (!in_readonly_region (memaddr
, length
))
1210 /* Otherwise we have a valid readonly case, fall through. */
1211 /* (assume no half-trace half-real blocks for now) */
1214 if (set_desired_process ())
1215 res
= read_inferior_memory (memaddr
, myaddr
, len
);
1219 return res
== 0 ? len
: -1;
1222 /* Write trace frame or inferior memory. Actually, writing to trace
1223 frames is forbidden. */
1226 gdb_write_memory (CORE_ADDR memaddr
, const unsigned char *myaddr
, int len
)
1228 client_state
&cs
= get_client_state ();
1229 if (cs
.current_traceframe
>= 0)
1235 if (set_desired_process ())
1236 ret
= target_write_memory (memaddr
, myaddr
, len
);
1243 /* Handle qSearch:memory packets. */
1246 handle_search_memory (char *own_buf
, int packet_len
)
1248 CORE_ADDR start_addr
;
1249 CORE_ADDR search_space_len
;
1251 unsigned int pattern_len
;
1253 CORE_ADDR found_addr
;
1254 int cmd_name_len
= sizeof ("qSearch:memory:") - 1;
1256 pattern
= (gdb_byte
*) malloc (packet_len
);
1257 if (pattern
== NULL
)
1258 error ("Unable to allocate memory to perform the search");
1260 if (decode_search_memory_packet (own_buf
+ cmd_name_len
,
1261 packet_len
- cmd_name_len
,
1262 &start_addr
, &search_space_len
,
1263 pattern
, &pattern_len
) < 0)
1266 error ("Error in parsing qSearch:memory packet");
1269 auto read_memory
= [] (CORE_ADDR addr
, gdb_byte
*result
, size_t len
)
1271 return gdb_read_memory (addr
, result
, len
) == len
;
1274 found
= simple_search_memory (read_memory
, start_addr
, search_space_len
,
1275 pattern
, pattern_len
, &found_addr
);
1278 sprintf (own_buf
, "1,%lx", (long) found_addr
);
1279 else if (found
== 0)
1280 strcpy (own_buf
, "0");
1282 strcpy (own_buf
, "E00");
1287 /* Handle the "D" packet. */
1290 handle_detach (char *own_buf
)
1292 client_state
&cs
= get_client_state ();
1294 process_info
*process
;
1296 if (cs
.multi_process
)
1299 int pid
= strtol (&own_buf
[2], NULL
, 16);
1301 process
= find_process_pid (pid
);
1304 process
= current_process ();
1306 if (process
== NULL
)
1308 write_enn (own_buf
);
1312 if ((tracing
&& disconnected_tracing
) || any_persistent_commands (process
))
1314 if (tracing
&& disconnected_tracing
)
1316 "Disconnected tracing in effect, "
1317 "leaving gdbserver attached to the process\n");
1319 if (any_persistent_commands (process
))
1321 "Persistent commands are present, "
1322 "leaving gdbserver attached to the process\n");
1324 /* Make sure we're in non-stop/async mode, so we we can both
1325 wait for an async socket accept, and handle async target
1326 events simultaneously. There's also no point either in
1327 having the target stop all threads, when we're going to
1328 pass signals down without informing GDB. */
1331 threads_debug_printf ("Forcing non-stop mode");
1334 the_target
->start_non_stop (true);
1337 process
->gdb_detached
= 1;
1339 /* Detaching implicitly resumes all threads. */
1340 target_continue_no_signal (minus_one_ptid
);
1346 fprintf (stderr
, "Detaching from process %d\n", process
->pid
);
1349 /* We'll need this after PROCESS has been destroyed. */
1350 int pid
= process
->pid
;
1352 /* If this process has an unreported fork child, that child is not known to
1353 GDB, so GDB won't take care of detaching it. We must do it here.
1355 Here, we specifically don't want to use "safe iteration", as detaching
1356 another process might delete the next thread in the iteration, which is
1357 the one saved by the safe iterator. We will never delete the currently
1358 iterated on thread, so standard iteration should be safe. */
1359 for (thread_info
&thread
: process
->thread_list ())
1361 /* Only threads that have a pending fork event. */
1362 target_waitkind kind
;
1363 thread_info
*child
= target_thread_pending_child (&thread
, &kind
);
1364 if (child
== nullptr || kind
== TARGET_WAITKIND_THREAD_CLONED
)
1367 process_info
*fork_child_process
= child
->process ();
1368 int fork_child_pid
= fork_child_process
->pid
;
1370 if (detach_inferior (fork_child_process
) != 0)
1371 warning (_("Failed to detach fork child %s, child of %s"),
1372 target_pid_to_str (ptid_t (fork_child_pid
)).c_str (),
1373 target_pid_to_str (thread
.id
).c_str ());
1376 if (detach_inferior (process
) != 0)
1377 write_enn (own_buf
);
1380 discard_queued_stop_replies (ptid_t (pid
));
1383 if (extended_protocol
|| target_running ())
1385 /* There is still at least one inferior remaining or
1386 we are in extended mode, so don't terminate gdbserver,
1387 and instead treat this like a normal program exit. */
1388 cs
.last_status
.set_exited (0);
1389 cs
.last_ptid
= ptid_t (pid
);
1391 switch_to_thread (nullptr);
1398 /* If we are attached, then we can exit. Otherwise, we
1399 need to hang around doing nothing, until the child is
1401 join_inferior (pid
);
1407 /* Parse options to --debug-format= and "monitor set debug-format".
1408 ARG is the text after "--debug-format=" or "monitor set debug-format".
1409 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1410 This triggers calls to monitor_output.
1411 The result is an empty string if all options were parsed ok, otherwise an
1412 error message which the caller must free.
1414 N.B. These commands affect all debug format settings, they are not
1415 cumulative. If a format is not specified, it is turned off.
1416 However, we don't go to extra trouble with things like
1417 "monitor set debug-format all,none,timestamp".
1418 Instead we just parse them one at a time, in order.
1420 The syntax for "monitor set debug" we support here is not identical
1421 to gdb's "set debug foo on|off" because we also use this function to
1422 parse "--debug-format=foo,bar". */
1425 parse_debug_format_options (const char *arg
, int is_monitor
)
1427 /* First turn all debug format options off. */
1428 debug_timestamp
= 0;
1430 /* First remove leading spaces, for "monitor set debug-format". */
1431 while (isspace (*arg
))
1434 std::vector
<gdb::unique_xmalloc_ptr
<char>> options
1435 = delim_string_to_char_ptr_vec (arg
, ',');
1437 for (const gdb::unique_xmalloc_ptr
<char> &option
: options
)
1439 if (strcmp (option
.get (), "all") == 0)
1441 debug_timestamp
= 1;
1443 monitor_output ("All extra debug format options enabled.\n");
1445 else if (strcmp (option
.get (), "none") == 0)
1447 debug_timestamp
= 0;
1449 monitor_output ("All extra debug format options disabled.\n");
1451 else if (strcmp (option
.get (), "timestamp") == 0)
1453 debug_timestamp
= 1;
1455 monitor_output ("Timestamps will be added to debug output.\n");
1457 else if (*option
== '\0')
1459 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1463 return string_printf ("Unknown debug-format argument: \"%s\"\n",
1467 return std::string ();
1470 /* A wrapper to enable, or disable a debug flag. These are debug flags
1471 that control the debug output from gdbserver, that developers might
1472 want, this is not something most end users will need. */
1476 /* NAME is the name of this debug option, this should be a simple string
1477 containing no whitespace, starting with a letter from isalpha(), and
1478 contain only isalnum() characters and '_' underscore and '-' hyphen.
1480 SETTER is a callback function used to set the debug variable. This
1481 callback will be passed true to enable the debug setting, or false to
1482 disable the debug setting. */
1483 debug_opt (const char *name
, std::function
<void (bool)> setter
)
1487 gdb_assert (isalpha (*name
));
1490 /* Called to enable or disable the debug setting. */
1491 void set (bool enable
) const
1496 /* Return the name of this debug option. */
1497 const char *name () const
1501 /* The name of this debug option. */
1504 /* The callback to update the debug setting. */
1505 std::function
<void (bool)> m_setter
;
1508 /* The set of all debug options that gdbserver supports. These are the
1509 options that can be passed to the command line '--debug=...' flag, or to
1510 the monitor command 'monitor set debug ...'. */
1512 static std::vector
<debug_opt
> all_debug_opt
{
1513 {"threads", [] (bool enable
)
1515 debug_threads
= enable
;
1517 {"remote", [] (bool enable
)
1519 remote_debug
= enable
;
1521 {"event-loop", [] (bool enable
)
1523 debug_event_loop
= (enable
? debug_event_loop_kind::ALL
1524 : debug_event_loop_kind::OFF
);
1528 /* Parse the options to --debug=...
1530 OPTIONS is the string of debug components which should be enabled (or
1531 disabled), and must not be nullptr. An empty OPTIONS string is valid,
1532 in which case a default set of debug components will be enabled.
1534 An unknown, or otherwise invalid debug component will result in an
1535 exception being thrown.
1537 OPTIONS can consist of multiple debug component names separated by a
1538 comma. Debugging for each component will be turned on. The special
1539 component 'all' can be used to enable debugging for all components.
1541 A component can also be prefixed with '-' to disable debugging of that
1542 component, so a user might use: '--debug=all,-remote', to enable all
1543 debugging, except for the remote (protocol) component. Components are
1544 processed left to write in the OPTIONS list. */
1547 parse_debug_options (const char *options
)
1549 gdb_assert (options
!= nullptr);
1551 /* Empty options means the "default" set. This exists mostly for
1552 backwards compatibility with gdbserver's legacy behavior. */
1553 if (*options
== '\0')
1554 options
= "+threads";
1556 while (*options
!= '\0')
1558 const char *end
= strchrnul (options
, ',');
1560 bool enable
= *options
!= '-';
1561 if (*options
== '-' || *options
== '+')
1564 std::string
opt (options
, end
- options
);
1566 if (opt
.size () == 0)
1567 error ("invalid empty debug option");
1569 bool is_opt_all
= opt
== "all";
1572 for (const auto &debug_opt
: all_debug_opt
)
1573 if (is_opt_all
|| opt
== debug_opt
.name ())
1575 debug_opt
.set (enable
);
1582 error ("unknown debug option '%s'", opt
.c_str ());
1584 options
= (*end
== ',') ? end
+ 1 : end
;
1588 /* Called from the 'monitor' command handler, to handle general 'set debug'
1589 monitor commands with one of the formats:
1591 set debug COMPONENT VALUE
1594 In both of these command formats VALUE can be 'on', 'off', '1', or '0'
1595 with 1/0 being equivalent to on/off respectively.
1597 In the no-COMPONENT version of the command, if VALUE is 'on' (or '1')
1598 then the component 'threads' is assumed, this is for backward
1599 compatibility, but maybe in the future we might find a better "default"
1600 set of debug flags to enable.
1602 In the no-COMPONENT version of the command, if VALUE is 'off' (or '0')
1603 then all debugging is turned off.
1605 Otherwise, COMPONENT must be one of the known debug components, and that
1606 component is either enabled or disabled as appropriate.
1608 The string MON contains either 'COMPONENT VALUE' or just the 'VALUE' for
1609 the second command format, the 'set debug ' has been stripped off
1612 Return a string containing an error message if something goes wrong,
1613 this error can be returned as part of the monitor command output. If
1614 everything goes correctly then the debug global will have been updated,
1615 and an empty string is returned. */
1618 handle_general_monitor_debug (const char *mon
)
1620 mon
= skip_spaces (mon
);
1623 return "No debug component name found.\n";
1625 /* Find the first word within MON. This is either the component name,
1626 or the value if no component has been given. */
1627 const char *end
= skip_to_space (mon
);
1628 std::string
component (mon
, end
- mon
);
1629 if (component
.find (',') != component
.npos
|| component
[0] == '-'
1630 || component
[0] == '+')
1631 return "Invalid character found in debug component name.\n";
1633 /* In ACTION_STR we create a string that will be passed to the
1634 parse_debug_options string. This will be either '+COMPONENT' or
1635 '-COMPONENT' depending on whether we want to enable or disable
1637 std::string action_str
;
1639 /* If parse_debug_options succeeds, then MSG will be returned to the user
1640 as the output of the monitor command. */
1643 /* Check for 'set debug off', this disables all debug output. */
1644 if (component
== "0" || component
== "off")
1646 if (*skip_spaces (end
) != '\0')
1647 return string_printf
1648 ("Junk '%s' found at end of 'set debug %s' command.\n",
1649 skip_spaces (end
), std::string (mon
, end
- mon
).c_str ());
1651 action_str
= "-all";
1652 msg
= "All debug output disabled.\n";
1654 /* Check for 'set debug on', this disables a general set of debug. */
1655 else if (component
== "1" || component
== "on")
1657 if (*skip_spaces (end
) != '\0')
1658 return string_printf
1659 ("Junk '%s' found at end of 'set debug %s' command.\n",
1660 skip_spaces (end
), std::string (mon
, end
- mon
).c_str ());
1662 action_str
= "+threads";
1663 msg
= "General debug output enabled.\n";
1665 /* Otherwise we should have 'set debug COMPONENT VALUE'. Extract the two
1666 parts and validate. */
1669 /* Figure out the value the user passed. */
1670 const char *value_start
= skip_spaces (end
);
1671 if (*value_start
== '\0')
1672 return string_printf ("Missing value for 'set debug %s' command.\n",
1675 const char *after_value
= skip_to_space (value_start
);
1676 if (*skip_spaces (after_value
) != '\0')
1677 return string_printf
1678 ("Junk '%s' found at end of 'set debug %s' command.\n",
1679 skip_spaces (after_value
),
1680 std::string (mon
, after_value
- mon
).c_str ());
1682 std::string
value (value_start
, after_value
- value_start
);
1684 /* Check VALUE to see if we are enabling, or disabling. */
1686 if (value
== "0" || value
== "off")
1688 else if (value
== "1" || value
== "on")
1691 return string_printf ("Invalid value '%s' for 'set debug %s'.\n",
1693 std::string (mon
, end
- mon
).c_str ());
1695 action_str
= std::string (enable
? "+" : "-") + component
;
1696 msg
= string_printf ("Debug output for '%s' %s.\n", component
.c_str (),
1697 enable
? "enabled" : "disabled");
1700 gdb_assert (!msg
.empty ());
1701 gdb_assert (!action_str
.empty ());
1705 parse_debug_options (action_str
.c_str ());
1706 monitor_output (msg
.c_str ());
1708 catch (const gdb_exception_error
&exception
)
1710 return string_printf ("Error: %s\n", exception
.what ());
1716 /* Handle monitor commands not handled by target-specific handlers. */
1719 handle_monitor_command (char *mon
, char *own_buf
)
1721 if (startswith (mon
, "set debug "))
1723 std::string error_msg
1724 = handle_general_monitor_debug (mon
+ sizeof ("set debug ") - 1);
1726 if (!error_msg
.empty ())
1728 monitor_output (error_msg
.c_str ());
1729 monitor_show_help ();
1730 write_enn (own_buf
);
1733 else if (strcmp (mon
, "set debug-hw-points 1") == 0)
1735 show_debug_regs
= 1;
1736 monitor_output ("H/W point debugging output enabled.\n");
1738 else if (strcmp (mon
, "set debug-hw-points 0") == 0)
1740 show_debug_regs
= 0;
1741 monitor_output ("H/W point debugging output disabled.\n");
1743 else if (startswith (mon
, "set debug-format "))
1745 std::string error_msg
1746 = parse_debug_format_options (mon
+ sizeof ("set debug-format ") - 1,
1749 if (!error_msg
.empty ())
1751 monitor_output (error_msg
.c_str ());
1752 monitor_show_help ();
1753 write_enn (own_buf
);
1756 else if (strcmp (mon
, "set debug-file") == 0)
1757 debug_set_output (nullptr);
1758 else if (startswith (mon
, "set debug-file "))
1759 debug_set_output (mon
+ sizeof ("set debug-file ") - 1);
1760 else if (strcmp (mon
, "help") == 0)
1761 monitor_show_help ();
1762 else if (strcmp (mon
, "exit") == 0)
1763 exit_requested
= true;
1766 monitor_output ("Unknown monitor command.\n\n");
1767 monitor_show_help ();
1768 write_enn (own_buf
);
1772 /* Associates a callback with each supported qXfer'able object. */
1776 /* The object this handler handles. */
1779 /* Request that the target transfer up to LEN 8-bit bytes of the
1780 target's OBJECT. The OFFSET, for a seekable object, specifies
1781 the starting point. The ANNEX can be used to provide additional
1782 data-specific information to the target.
1784 Return the number of bytes actually transferred, zero when no
1785 further transfer is possible, -1 on error, -2 when the transfer
1786 is not supported, and -3 on a verbose error message that should
1787 be preserved. Return of a positive value smaller than LEN does
1788 not indicate the end of the object, only the end of the transfer.
1790 One, and only one, of readbuf or writebuf must be non-NULL. */
1791 int (*xfer
) (const char *annex
,
1792 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1793 ULONGEST offset
, LONGEST len
);
1796 /* Handle qXfer:auxv:read. */
1799 handle_qxfer_auxv (const char *annex
,
1800 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1801 ULONGEST offset
, LONGEST len
)
1803 if (!the_target
->supports_read_auxv () || writebuf
!= NULL
)
1806 if (annex
[0] != '\0' || current_thread
== NULL
)
1809 return the_target
->read_auxv (current_thread
->id
.pid (), offset
, readbuf
,
1813 /* Handle qXfer:exec-file:read. */
1816 handle_qxfer_exec_file (const char *annex
,
1817 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1818 ULONGEST offset
, LONGEST len
)
1823 if (!the_target
->supports_pid_to_exec_file () || writebuf
!= NULL
)
1826 if (annex
[0] == '\0')
1828 if (current_thread
== NULL
)
1831 pid
= current_thread
->id
.pid ();
1835 annex
= unpack_varlen_hex (annex
, &pid
);
1836 if (annex
[0] != '\0')
1843 const char *file
= the_target
->pid_to_exec_file (pid
);
1847 total_len
= strlen (file
);
1849 if (offset
> total_len
)
1852 if (offset
+ len
> total_len
)
1853 len
= total_len
- offset
;
1855 memcpy (readbuf
, file
+ offset
, len
);
1859 /* Handle qXfer:features:read. */
1862 handle_qxfer_features (const char *annex
,
1863 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1864 ULONGEST offset
, LONGEST len
)
1866 const char *document
;
1869 if (writebuf
!= NULL
)
1872 if (!target_running ())
1875 /* Grab the correct annex. */
1876 document
= get_features_xml (annex
);
1877 if (document
== NULL
)
1880 total_len
= strlen (document
);
1882 if (offset
> total_len
)
1885 if (offset
+ len
> total_len
)
1886 len
= total_len
- offset
;
1888 memcpy (readbuf
, document
+ offset
, len
);
1892 /* Handle qXfer:libraries:read. */
1895 handle_qxfer_libraries (const char *annex
,
1896 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1897 ULONGEST offset
, LONGEST len
)
1899 if (writebuf
!= NULL
)
1902 if (annex
[0] != '\0' || current_thread
== NULL
)
1905 std::string document
= "<library-list version=\"1.0\">\n";
1907 process_info
*proc
= current_process ();
1908 for (const dll_info
&dll
: proc
->all_dlls
)
1909 document
+= string_printf
1910 (" <library name=\"%s\"><segment address=\"0x%s\"/></library>\n",
1911 dll
.name
.c_str (), paddress (dll
.base_addr
));
1913 document
+= "</library-list>\n";
1915 if (offset
> document
.length ())
1918 if (offset
+ len
> document
.length ())
1919 len
= document
.length () - offset
;
1921 memcpy (readbuf
, &document
[offset
], len
);
1926 /* Handle qXfer:libraries-svr4:read. */
1929 handle_qxfer_libraries_svr4 (const char *annex
,
1930 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1931 ULONGEST offset
, LONGEST len
)
1933 if (writebuf
!= NULL
)
1936 if (current_thread
== NULL
1937 || !the_target
->supports_qxfer_libraries_svr4 ())
1940 return the_target
->qxfer_libraries_svr4 (annex
, readbuf
, writebuf
,
1944 /* Handle qXfer:osadata:read. */
1947 handle_qxfer_osdata (const char *annex
,
1948 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1949 ULONGEST offset
, LONGEST len
)
1951 if (!the_target
->supports_qxfer_osdata () || writebuf
!= NULL
)
1954 return the_target
->qxfer_osdata (annex
, readbuf
, NULL
, offset
, len
);
1957 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1960 handle_qxfer_siginfo (const char *annex
,
1961 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1962 ULONGEST offset
, LONGEST len
)
1964 if (!the_target
->supports_qxfer_siginfo ())
1967 if (annex
[0] != '\0' || current_thread
== NULL
)
1970 return the_target
->qxfer_siginfo (annex
, readbuf
, writebuf
, offset
, len
);
1973 /* Helper for handle_qxfer_threads_proper.
1974 Emit the XML to describe the thread of INF. */
1977 handle_qxfer_threads_worker (thread_info
*thread
, std::string
*buffer
)
1979 ptid_t ptid
= thread
->id
;
1981 int core
= target_core_of_thread (ptid
);
1983 const char *name
= target_thread_name (ptid
);
1986 bool handle_status
= target_thread_handle (ptid
, &handle
, &handle_len
);
1988 /* If this is a (v)fork/clone child (has a (v)fork/clone parent),
1989 GDB does not yet know about this thread, and must not know about
1990 it until it gets the corresponding (v)fork/clone event. Exclude
1991 this thread from the list. */
1992 if (target_thread_pending_parent (thread
) != nullptr)
1995 write_ptid (ptid_s
, ptid
);
1997 string_xml_appendf (*buffer
, "<thread id=\"%s\"", ptid_s
);
2001 sprintf (core_s
, "%d", core
);
2002 string_xml_appendf (*buffer
, " core=\"%s\"", core_s
);
2006 string_xml_appendf (*buffer
, " name=\"%s\"", name
);
2010 char *handle_s
= (char *) alloca (handle_len
* 2 + 1);
2011 bin2hex (handle
, handle_s
, handle_len
);
2012 string_xml_appendf (*buffer
, " handle=\"%s\"", handle_s
);
2015 string_xml_appendf (*buffer
, "/>\n");
2018 /* Helper for handle_qxfer_threads. Return true on success, false
2022 handle_qxfer_threads_proper (std::string
*buffer
)
2024 *buffer
+= "<threads>\n";
2026 /* The target may need to access memory and registers (e.g. via
2027 libthread_db) to fetch thread properties. Even if don't need to
2028 stop threads to access memory, we still will need to be able to
2029 access registers, and other ptrace accesses like
2030 PTRACE_GET_THREAD_AREA that require a paused thread. Pause all
2031 threads here, so that we pause each thread at most once for all
2034 target_pause_all (true);
2036 for_each_thread ([&] (thread_info
*thread
)
2038 handle_qxfer_threads_worker (thread
, buffer
);
2042 target_unpause_all (true);
2044 *buffer
+= "</threads>\n";
2048 /* Handle qXfer:threads:read. */
2051 handle_qxfer_threads (const char *annex
,
2052 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2053 ULONGEST offset
, LONGEST len
)
2055 static std::string result
;
2057 if (writebuf
!= NULL
)
2060 if (annex
[0] != '\0')
2065 /* When asked for data at offset 0, generate everything and store into
2066 'result'. Successive reads will be served off 'result'. */
2069 bool res
= handle_qxfer_threads_proper (&result
);
2075 if (offset
>= result
.length ())
2077 /* We're out of data. */
2082 if (len
> result
.length () - offset
)
2083 len
= result
.length () - offset
;
2085 memcpy (readbuf
, result
.c_str () + offset
, len
);
2090 /* Handle qXfer:traceframe-info:read. */
2093 handle_qxfer_traceframe_info (const char *annex
,
2094 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2095 ULONGEST offset
, LONGEST len
)
2097 client_state
&cs
= get_client_state ();
2098 static std::string result
;
2100 if (writebuf
!= NULL
)
2103 if (!target_running () || annex
[0] != '\0' || cs
.current_traceframe
== -1)
2108 /* When asked for data at offset 0, generate everything and
2109 store into 'result'. Successive reads will be served off
2113 traceframe_read_info (cs
.current_traceframe
, &result
);
2116 if (offset
>= result
.length ())
2118 /* We're out of data. */
2123 if (len
> result
.length () - offset
)
2124 len
= result
.length () - offset
;
2126 memcpy (readbuf
, result
.c_str () + offset
, len
);
2130 /* Handle qXfer:fdpic:read. */
2133 handle_qxfer_fdpic (const char *annex
, gdb_byte
*readbuf
,
2134 const gdb_byte
*writebuf
, ULONGEST offset
, LONGEST len
)
2136 if (!the_target
->supports_read_loadmap ())
2139 if (current_thread
== NULL
)
2142 return the_target
->read_loadmap (annex
, offset
, readbuf
, len
);
2145 /* Handle qXfer:btrace:read. */
2148 handle_qxfer_btrace (const char *annex
,
2149 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2150 ULONGEST offset
, LONGEST len
)
2152 client_state
&cs
= get_client_state ();
2153 static std::string cache
;
2154 thread_info
*thread
;
2155 enum btrace_read_type type
;
2158 if (writebuf
!= NULL
)
2161 if (cs
.general_thread
== null_ptid
2162 || cs
.general_thread
== minus_one_ptid
)
2164 strcpy (cs
.own_buf
, "E.Must select a single thread.");
2168 thread
= find_thread_ptid (cs
.general_thread
);
2171 strcpy (cs
.own_buf
, "E.No such thread.");
2175 if (thread
->btrace
== NULL
)
2177 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
2181 if (strcmp (annex
, "all") == 0)
2182 type
= BTRACE_READ_ALL
;
2183 else if (strcmp (annex
, "new") == 0)
2184 type
= BTRACE_READ_NEW
;
2185 else if (strcmp (annex
, "delta") == 0)
2186 type
= BTRACE_READ_DELTA
;
2189 strcpy (cs
.own_buf
, "E.Bad annex.");
2199 result
= target_read_btrace (thread
->btrace
, &cache
, type
);
2201 memcpy (cs
.own_buf
, cache
.c_str (), cache
.length ());
2203 catch (const gdb_exception_error
&exception
)
2205 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
2212 else if (offset
> cache
.length ())
2218 if (len
> cache
.length () - offset
)
2219 len
= cache
.length () - offset
;
2221 memcpy (readbuf
, cache
.c_str () + offset
, len
);
2226 /* Handle qXfer:btrace-conf:read. */
2229 handle_qxfer_btrace_conf (const char *annex
,
2230 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2231 ULONGEST offset
, LONGEST len
)
2233 client_state
&cs
= get_client_state ();
2234 static std::string cache
;
2235 thread_info
*thread
;
2238 if (writebuf
!= NULL
)
2241 if (annex
[0] != '\0')
2244 if (cs
.general_thread
== null_ptid
2245 || cs
.general_thread
== minus_one_ptid
)
2247 strcpy (cs
.own_buf
, "E.Must select a single thread.");
2251 thread
= find_thread_ptid (cs
.general_thread
);
2254 strcpy (cs
.own_buf
, "E.No such thread.");
2258 if (thread
->btrace
== NULL
)
2260 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
2270 result
= target_read_btrace_conf (thread
->btrace
, &cache
);
2272 memcpy (cs
.own_buf
, cache
.c_str (), cache
.length ());
2274 catch (const gdb_exception_error
&exception
)
2276 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
2283 else if (offset
> cache
.length ())
2289 if (len
> cache
.length () - offset
)
2290 len
= cache
.length () - offset
;
2292 memcpy (readbuf
, cache
.c_str () + offset
, len
);
2297 static const struct qxfer qxfer_packets
[] =
2299 { "auxv", handle_qxfer_auxv
},
2300 { "btrace", handle_qxfer_btrace
},
2301 { "btrace-conf", handle_qxfer_btrace_conf
},
2302 { "exec-file", handle_qxfer_exec_file
},
2303 { "fdpic", handle_qxfer_fdpic
},
2304 { "features", handle_qxfer_features
},
2305 { "libraries", handle_qxfer_libraries
},
2306 { "libraries-svr4", handle_qxfer_libraries_svr4
},
2307 { "osdata", handle_qxfer_osdata
},
2308 { "siginfo", handle_qxfer_siginfo
},
2309 { "threads", handle_qxfer_threads
},
2310 { "traceframe-info", handle_qxfer_traceframe_info
},
2314 handle_qxfer (char *own_buf
, int packet_len
, int *new_packet_len_p
)
2322 if (!startswith (own_buf
, "qXfer:"))
2325 /* Grab the object, r/w and annex. */
2326 if (decode_xfer (own_buf
+ 6, &object
, &rw
, &annex
, &offset
) < 0)
2328 write_enn (own_buf
);
2333 i
< sizeof (qxfer_packets
) / sizeof (qxfer_packets
[0]);
2336 const struct qxfer
*q
= &qxfer_packets
[i
];
2338 if (strcmp (object
, q
->object
) == 0)
2340 if (strcmp (rw
, "read") == 0)
2342 unsigned char *data
;
2347 /* Grab the offset and length. */
2348 if (decode_xfer_read (offset
, &ofs
, &len
) < 0)
2350 write_enn (own_buf
);
2354 /* Read one extra byte, as an indicator of whether there is
2356 if (len
> PBUFSIZ
- 2)
2358 data
= (unsigned char *) malloc (len
+ 1);
2361 write_enn (own_buf
);
2364 n
= (*q
->xfer
) (annex
, data
, NULL
, ofs
, len
+ 1);
2372 /* Preserve error message. */
2375 write_enn (own_buf
);
2377 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, len
, 1);
2379 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, n
, 0);
2384 else if (strcmp (rw
, "write") == 0)
2389 unsigned char *data
;
2391 strcpy (own_buf
, "E00");
2392 data
= (unsigned char *) malloc (packet_len
- (offset
- own_buf
));
2395 write_enn (own_buf
);
2398 if (decode_xfer_write (offset
, packet_len
- (offset
- own_buf
),
2399 &ofs
, &len
, data
) < 0)
2402 write_enn (own_buf
);
2406 n
= (*q
->xfer
) (annex
, NULL
, data
, ofs
, len
);
2414 /* Preserve error message. */
2417 write_enn (own_buf
);
2419 sprintf (own_buf
, "%x", n
);
2432 /* Compute 32 bit CRC from inferior memory.
2434 On success, return 32 bit CRC.
2435 On failure, return (unsigned long long) -1. */
2437 static unsigned long long
2438 crc32 (CORE_ADDR base
, int len
, unsigned int crc
)
2442 unsigned char byte
= 0;
2444 /* Return failure if memory read fails. */
2445 if (read_inferior_memory (base
, &byte
, 1) != 0)
2446 return (unsigned long long) -1;
2448 crc
= xcrc32 (&byte
, 1, crc
);
2451 return (unsigned long long) crc
;
2454 /* Parse the qMemTags packet request into ADDR and LEN. */
2457 parse_fetch_memtags_request (char *request
, CORE_ADDR
*addr
, size_t *len
,
2460 gdb_assert (startswith (request
, "qMemTags:"));
2462 const char *p
= request
+ strlen ("qMemTags:");
2464 /* Read address and length. */
2465 unsigned int length
= 0;
2466 p
= decode_m_packet_params (p
, addr
, &length
, ':');
2469 /* Read the tag type. */
2470 ULONGEST tag_type
= 0;
2471 p
= unpack_varlen_hex (p
, &tag_type
);
2472 *type
= (int) tag_type
;
2475 /* Add supported btrace packets to BUF. */
2478 supported_btrace_packets (char *buf
)
2480 strcat (buf
, ";Qbtrace:bts+");
2481 strcat (buf
, ";Qbtrace-conf:bts:size+");
2482 strcat (buf
, ";Qbtrace:pt+");
2483 strcat (buf
, ";Qbtrace-conf:pt:size+");
2484 strcat (buf
, ";Qbtrace-conf:pt:ptwrite+");
2485 strcat (buf
, ";Qbtrace-conf:pt:event-tracing+");
2486 strcat (buf
, ";Qbtrace:off+");
2487 strcat (buf
, ";qXfer:btrace:read+");
2488 strcat (buf
, ";qXfer:btrace-conf:read+");
2491 /* Handle all of the extended 'q' packets. */
2494 handle_query (char *own_buf
, int packet_len
, int *new_packet_len_p
)
2496 client_state
&cs
= get_client_state ();
2497 static owning_intrusive_list
<process_info
>::iterator process_iter
;
2498 static owning_intrusive_list
<thread_info
>::iterator thread_iter
;
2500 auto init_thread_iter
= [&] ()
2502 process_iter
= all_processes
.begin ();
2503 owning_intrusive_list
<thread_info
> *thread_list
;
2505 for (; process_iter
!= all_processes
.end (); ++process_iter
)
2507 thread_list
= &process_iter
->thread_list ();
2508 thread_iter
= thread_list
->begin ();
2509 if (thread_iter
!= thread_list
->end ())
2512 /* Make sure that there is at least one thread to iterate. */
2513 gdb_assert (process_iter
!= all_processes
.end ());
2514 gdb_assert (thread_iter
!= thread_list
->end ());
2517 auto advance_thread_iter
= [&] ()
2519 /* The loop below is written in the natural way as-if we'd always
2520 start at the beginning of the inferior list. This fast forwards
2521 the algorithm to the actual current position. */
2522 owning_intrusive_list
<thread_info
> *thread_list
2523 = &process_iter
->thread_list ();
2526 for (; process_iter
!= all_processes
.end (); ++process_iter
)
2528 thread_list
= &process_iter
->thread_list ();
2529 thread_iter
= thread_list
->begin ();
2530 while (thread_iter
!= thread_list
->end ())
2539 /* Reply the current thread id. */
2540 if (strcmp ("qC", own_buf
) == 0 && !disable_packet_qC
)
2543 require_running_or_return (own_buf
);
2545 if (cs
.general_thread
!= null_ptid
&& cs
.general_thread
!= minus_one_ptid
)
2546 ptid
= cs
.general_thread
;
2549 init_thread_iter ();
2550 ptid
= thread_iter
->id
;
2553 sprintf (own_buf
, "QC");
2555 write_ptid (own_buf
, ptid
);
2559 if (strcmp ("qSymbol::", own_buf
) == 0)
2561 scoped_restore_current_thread restore_thread
;
2563 /* For qSymbol, GDB only changes the current thread if the
2564 previous current thread was of a different process. So if
2565 the previous thread is gone, we need to pick another one of
2566 the same process. This can happen e.g., if we followed an
2567 exec in a non-leader thread. */
2568 if (current_thread
== NULL
)
2570 thread_info
*any_thread
2571 = find_any_thread_of_pid (cs
.general_thread
.pid ());
2572 switch_to_thread (any_thread
);
2574 /* Just in case, if we didn't find a thread, then bail out
2575 instead of crashing. */
2576 if (current_thread
== NULL
)
2578 write_enn (own_buf
);
2583 /* GDB is suggesting new symbols have been loaded. This may
2584 mean a new shared library has been detected as loaded, so
2585 take the opportunity to check if breakpoints we think are
2586 inserted, still are. Note that it isn't guaranteed that
2587 we'll see this when a shared library is loaded, and nor will
2588 we see this for unloads (although breakpoints in unloaded
2589 libraries shouldn't trigger), as GDB may not find symbols for
2590 the library at all. We also re-validate breakpoints when we
2591 see a second GDB breakpoint for the same address, and or when
2592 we access breakpoint shadows. */
2593 validate_breakpoints ();
2595 if (target_supports_tracepoints ())
2596 tracepoint_look_up_symbols ();
2598 if (current_thread
!= NULL
)
2599 the_target
->look_up_symbols ();
2601 strcpy (own_buf
, "OK");
2605 if (!disable_packet_qfThreadInfo
)
2607 if (strcmp ("qfThreadInfo", own_buf
) == 0)
2609 require_running_or_return (own_buf
);
2610 init_thread_iter ();
2613 ptid_t ptid
= thread_iter
->id
;
2614 write_ptid (own_buf
, ptid
);
2615 advance_thread_iter ();
2619 if (strcmp ("qsThreadInfo", own_buf
) == 0)
2621 require_running_or_return (own_buf
);
2622 /* We're done if the process iterator hits the end of the
2624 if (process_iter
!= all_processes
.end ())
2627 ptid_t ptid
= thread_iter
->id
;
2628 write_ptid (own_buf
, ptid
);
2629 advance_thread_iter ();
2634 sprintf (own_buf
, "l");
2640 if (the_target
->supports_read_offsets ()
2641 && strcmp ("qOffsets", own_buf
) == 0)
2643 CORE_ADDR text
, data
;
2645 require_running_or_return (own_buf
);
2646 if (the_target
->read_offsets (&text
, &data
))
2647 sprintf (own_buf
, "Text=%lX;Data=%lX;Bss=%lX",
2648 (long)text
, (long)data
, (long)data
);
2650 write_enn (own_buf
);
2655 /* Protocol features query. */
2656 if (startswith (own_buf
, "qSupported")
2657 && (own_buf
[10] == ':' || own_buf
[10] == '\0'))
2659 char *p
= &own_buf
[10];
2660 int gdb_supports_qRelocInsn
= 0;
2662 /* Process each feature being provided by GDB. The first
2663 feature will follow a ':', and latter features will follow
2667 std::vector
<std::string
> qsupported
;
2668 std::vector
<const char *> unknowns
;
2670 /* Two passes, to avoid nested strtok calls in
2671 target_process_qsupported. */
2673 for (p
= strtok_r (p
+ 1, ";", &saveptr
);
2675 p
= strtok_r (NULL
, ";", &saveptr
))
2676 qsupported
.emplace_back (p
);
2678 for (const std::string
&feature
: qsupported
)
2680 if (feature
== "multiprocess+")
2682 /* GDB supports and wants multi-process support if
2684 if (target_supports_multi_process ())
2685 cs
.multi_process
= 1;
2687 else if (feature
== "qRelocInsn+")
2689 /* GDB supports relocate instruction requests. */
2690 gdb_supports_qRelocInsn
= 1;
2692 else if (feature
== "swbreak+")
2694 /* GDB wants us to report whether a trap is caused
2695 by a software breakpoint and for us to handle PC
2696 adjustment if necessary on this target. */
2697 if (target_supports_stopped_by_sw_breakpoint ())
2698 cs
.swbreak_feature
= 1;
2700 else if (feature
== "hwbreak+")
2702 /* GDB wants us to report whether a trap is caused
2703 by a hardware breakpoint. */
2704 if (target_supports_stopped_by_hw_breakpoint ())
2705 cs
.hwbreak_feature
= 1;
2707 else if (feature
== "fork-events+")
2709 /* GDB supports and wants fork events if possible. */
2710 if (target_supports_fork_events ())
2711 cs
.report_fork_events
= 1;
2713 else if (feature
== "vfork-events+")
2715 /* GDB supports and wants vfork events if possible. */
2716 if (target_supports_vfork_events ())
2717 cs
.report_vfork_events
= 1;
2719 else if (feature
== "exec-events+")
2721 /* GDB supports and wants exec events if possible. */
2722 if (target_supports_exec_events ())
2723 cs
.report_exec_events
= 1;
2725 else if (feature
== "vContSupported+")
2726 cs
.vCont_supported
= 1;
2727 else if (feature
== "QThreadEvents+")
2729 else if (feature
== "QThreadOptions+")
2731 else if (feature
== "no-resumed+")
2733 /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
2735 report_no_resumed
= true;
2737 else if (feature
== "memory-tagging+")
2739 /* GDB supports memory tagging features. */
2740 if (target_supports_memory_tagging ())
2741 cs
.memory_tagging_feature
= true;
2743 else if (feature
== "error-message+")
2744 cs
.error_message_supported
= true;
2747 /* Move the unknown features all together. */
2748 unknowns
.push_back (feature
.c_str ());
2752 /* Give the target backend a chance to process the unknown
2754 target_process_qsupported (unknowns
);
2758 "PacketSize=%x;QPassSignals+;QProgramSignals+;"
2759 "QStartupWithShell+;QEnvironmentHexEncoded+;"
2760 "QEnvironmentReset+;QEnvironmentUnset+;"
2761 "QSetWorkingDir+;binary-upload+",
2764 if (target_supports_catch_syscall ())
2765 strcat (own_buf
, ";QCatchSyscalls+");
2767 if (the_target
->supports_qxfer_libraries_svr4 ())
2768 strcat (own_buf
, ";qXfer:libraries-svr4:read+"
2769 ";augmented-libraries-svr4-read+");
2772 /* We do not have any hook to indicate whether the non-SVR4 target
2773 backend supports qXfer:libraries:read, so always report it. */
2774 strcat (own_buf
, ";qXfer:libraries:read+");
2777 if (the_target
->supports_read_auxv ())
2778 strcat (own_buf
, ";qXfer:auxv:read+");
2780 if (the_target
->supports_qxfer_siginfo ())
2781 strcat (own_buf
, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2783 if (the_target
->supports_read_loadmap ())
2784 strcat (own_buf
, ";qXfer:fdpic:read+");
2786 /* We always report qXfer:features:read, as targets may
2787 install XML files on a subsequent call to arch_setup.
2788 If we reported to GDB on startup that we don't support
2789 qXfer:feature:read at all, we will never be re-queried. */
2790 strcat (own_buf
, ";qXfer:features:read+");
2792 if (cs
.transport_is_reliable
)
2793 strcat (own_buf
, ";QStartNoAckMode+");
2795 if (the_target
->supports_qxfer_osdata ())
2796 strcat (own_buf
, ";qXfer:osdata:read+");
2798 if (target_supports_multi_process ())
2799 strcat (own_buf
, ";multiprocess+");
2801 if (target_supports_fork_events ())
2802 strcat (own_buf
, ";fork-events+");
2804 if (target_supports_vfork_events ())
2805 strcat (own_buf
, ";vfork-events+");
2807 if (target_supports_exec_events ())
2808 strcat (own_buf
, ";exec-events+");
2810 if (target_supports_non_stop ())
2811 strcat (own_buf
, ";QNonStop+");
2813 if (target_supports_disable_randomization ())
2814 strcat (own_buf
, ";QDisableRandomization+");
2816 strcat (own_buf
, ";qXfer:threads:read+");
2818 if (target_supports_tracepoints ())
2820 strcat (own_buf
, ";ConditionalTracepoints+");
2821 strcat (own_buf
, ";TraceStateVariables+");
2822 strcat (own_buf
, ";TracepointSource+");
2823 strcat (own_buf
, ";DisconnectedTracing+");
2824 if (gdb_supports_qRelocInsn
&& target_supports_fast_tracepoints ())
2825 strcat (own_buf
, ";FastTracepoints+");
2826 strcat (own_buf
, ";InstallInTrace+");
2827 strcat (own_buf
, ";qXfer:traceframe-info:read+");
2828 strcat (own_buf
, ";EnableDisableTracepoints+");
2829 strcat (own_buf
, ";QTBuffer:size+");
2830 strcat (own_buf
, ";tracenz+");
2833 if (target_supports_hardware_single_step ()
2834 || target_supports_software_single_step () )
2836 strcat (own_buf
, ";ConditionalBreakpoints+");
2838 strcat (own_buf
, ";BreakpointCommands+");
2840 if (target_supports_agent ())
2841 strcat (own_buf
, ";QAgent+");
2843 if (the_target
->supports_btrace ())
2844 supported_btrace_packets (own_buf
);
2846 if (target_supports_stopped_by_sw_breakpoint ())
2847 strcat (own_buf
, ";swbreak+");
2849 if (target_supports_stopped_by_hw_breakpoint ())
2850 strcat (own_buf
, ";hwbreak+");
2852 if (the_target
->supports_pid_to_exec_file ())
2853 strcat (own_buf
, ";qXfer:exec-file:read+");
2855 strcat (own_buf
, ";vContSupported+");
2857 gdb_thread_options supported_options
= target_supported_thread_options ();
2858 if (supported_options
!= 0)
2860 char *end_buf
= own_buf
+ strlen (own_buf
);
2861 sprintf (end_buf
, ";QThreadOptions=%s",
2862 phex_nz (supported_options
, sizeof (supported_options
)));
2865 strcat (own_buf
, ";QThreadEvents+");
2867 strcat (own_buf
, ";no-resumed+");
2869 if (target_supports_memory_tagging ())
2870 strcat (own_buf
, ";memory-tagging+");
2872 /* Reinitialize components as needed for the new connection. */
2873 hostio_handle_new_gdb_connection ();
2874 target_handle_new_gdb_connection ();
2879 /* Thread-local storage support. */
2880 if (the_target
->supports_get_tls_address ()
2881 && startswith (own_buf
, "qGetTLSAddr:"))
2883 char *p
= own_buf
+ 12;
2884 CORE_ADDR parts
[2], address
= 0;
2886 ptid_t ptid
= null_ptid
;
2888 require_running_or_return (own_buf
);
2890 for (i
= 0; i
< 3; i
++)
2898 p2
= strchr (p
, ',');
2911 ptid
= read_ptid (p
, NULL
);
2913 decode_address (&parts
[i
- 1], p
, len
);
2917 if (p
!= NULL
|| i
< 3)
2921 thread_info
*thread
= find_thread_ptid (ptid
);
2926 err
= the_target
->get_tls_address (thread
, parts
[0], parts
[1],
2932 strcpy (own_buf
, paddress(address
));
2937 write_enn (own_buf
);
2941 /* Otherwise, pretend we do not understand this packet. */
2944 /* Windows OS Thread Information Block address support. */
2945 if (the_target
->supports_get_tib_address ()
2946 && startswith (own_buf
, "qGetTIBAddr:"))
2951 ptid_t ptid
= read_ptid (own_buf
+ 12, &annex
);
2953 n
= the_target
->get_tib_address (ptid
, &tlb
);
2956 strcpy (own_buf
, paddress(tlb
));
2961 write_enn (own_buf
);
2967 /* Handle "monitor" commands. */
2968 if (startswith (own_buf
, "qRcmd,"))
2970 char *mon
= (char *) malloc (PBUFSIZ
);
2971 int len
= strlen (own_buf
+ 6);
2975 write_enn (own_buf
);
2980 || hex2bin (own_buf
+ 6, (gdb_byte
*) mon
, len
/ 2) != len
/ 2)
2982 write_enn (own_buf
);
2986 mon
[len
/ 2] = '\0';
2990 if (the_target
->handle_monitor_command (mon
) == 0)
2991 /* Default processing. */
2992 handle_monitor_command (mon
, own_buf
);
2998 if (startswith (own_buf
, "qSearch:memory:"))
3000 require_running_or_return (own_buf
);
3001 handle_search_memory (own_buf
, packet_len
);
3005 if (strcmp (own_buf
, "qAttached") == 0
3006 || startswith (own_buf
, "qAttached:"))
3008 struct process_info
*process
;
3010 if (own_buf
[sizeof ("qAttached") - 1])
3012 int pid
= strtoul (own_buf
+ sizeof ("qAttached:") - 1, NULL
, 16);
3013 process
= find_process_pid (pid
);
3017 require_running_or_return (own_buf
);
3018 process
= current_process ();
3021 if (process
== NULL
)
3023 write_enn (own_buf
);
3027 strcpy (own_buf
, process
->attached
? "1" : "0");
3031 if (startswith (own_buf
, "qCRC:"))
3033 /* CRC check (compare-section). */
3037 unsigned long long crc
;
3039 require_running_or_return (own_buf
);
3040 comma
= unpack_varlen_hex (own_buf
+ 5, &base
);
3041 if (*comma
++ != ',')
3043 write_enn (own_buf
);
3046 len
= strtoul (comma
, NULL
, 16);
3047 crc
= crc32 (base
, len
, 0xffffffff);
3048 /* Check for memory failure. */
3049 if (crc
== (unsigned long long) -1)
3051 write_enn (own_buf
);
3054 sprintf (own_buf
, "C%lx", (unsigned long) crc
);
3058 if (handle_qxfer (own_buf
, packet_len
, new_packet_len_p
))
3061 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf
))
3064 /* Handle fetch memory tags packets. */
3065 if (startswith (own_buf
, "qMemTags:")
3066 && target_supports_memory_tagging ())
3068 gdb::byte_vector tags
;
3073 require_running_or_return (own_buf
);
3075 parse_fetch_memtags_request (own_buf
, &addr
, &len
, &type
);
3077 bool ret
= the_target
->fetch_memtags (addr
, len
, tags
, type
);
3080 ret
= create_fetch_memtags_reply (own_buf
, tags
);
3083 write_enn (own_buf
);
3085 *new_packet_len_p
= strlen (own_buf
);
3089 /* Otherwise we didn't know what packet it was. Say we didn't
3094 static void gdb_wants_all_threads_stopped (void);
3095 static void resume (struct thread_resume
*actions
, size_t n
);
3097 /* The callback that is passed to visit_actioned_threads. */
3098 typedef int (visit_actioned_threads_callback_ftype
)
3099 (const struct thread_resume
*, thread_info
*);
3101 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
3102 true if CALLBACK returns true. Returns false if no matching thread
3103 is found or CALLBACK results false.
3104 Note: This function is itself a callback for find_thread. */
3107 visit_actioned_threads (thread_info
*thread
,
3108 const struct thread_resume
*actions
,
3110 visit_actioned_threads_callback_ftype
*callback
)
3112 for (size_t i
= 0; i
< num_actions
; i
++)
3114 const struct thread_resume
*action
= &actions
[i
];
3116 if (action
->thread
== minus_one_ptid
3117 || action
->thread
== thread
->id
3118 || ((action
->thread
.pid ()
3119 == thread
->id
.pid ())
3120 && action
->thread
.lwp () == -1))
3122 if ((*callback
) (action
, thread
))
3130 /* Callback for visit_actioned_threads. If the thread has a pending
3131 status to report, report it now. */
3134 handle_pending_status (const struct thread_resume
*resumption
,
3135 thread_info
*thread
)
3137 client_state
&cs
= get_client_state ();
3138 if (thread
->status_pending_p
)
3140 thread
->status_pending_p
= 0;
3142 cs
.last_status
= thread
->last_status
;
3143 cs
.last_ptid
= thread
->id
;
3144 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, cs
.last_status
);
3150 /* Parse vCont packets. */
3152 handle_v_cont (char *own_buf
)
3156 struct thread_resume
*resume_info
;
3157 struct thread_resume default_action
{ null_ptid
};
3159 /* Count the number of semicolons in the packet. There should be one
3160 for every action. */
3166 p
= strchr (p
, ';');
3169 resume_info
= (struct thread_resume
*) malloc (n
* sizeof (resume_info
[0]));
3170 if (resume_info
== NULL
)
3178 memset (&resume_info
[i
], 0, sizeof resume_info
[i
]);
3180 if (p
[0] == 's' || p
[0] == 'S')
3181 resume_info
[i
].kind
= resume_step
;
3182 else if (p
[0] == 'r')
3183 resume_info
[i
].kind
= resume_step
;
3184 else if (p
[0] == 'c' || p
[0] == 'C')
3185 resume_info
[i
].kind
= resume_continue
;
3186 else if (p
[0] == 't')
3187 resume_info
[i
].kind
= resume_stop
;
3191 if (p
[0] == 'S' || p
[0] == 'C')
3194 int sig
= strtol (p
+ 1, &q
, 16);
3199 if (!gdb_signal_to_host_p ((enum gdb_signal
) sig
))
3201 resume_info
[i
].sig
= gdb_signal_to_host ((enum gdb_signal
) sig
);
3203 else if (p
[0] == 'r')
3207 p
= unpack_varlen_hex (p
+ 1, &addr
);
3208 resume_info
[i
].step_range_start
= addr
;
3213 p
= unpack_varlen_hex (p
+ 1, &addr
);
3214 resume_info
[i
].step_range_end
= addr
;
3223 resume_info
[i
].thread
= minus_one_ptid
;
3224 default_action
= resume_info
[i
];
3226 /* Note: we don't increment i here, we'll overwrite this entry
3227 the next time through. */
3229 else if (p
[0] == ':')
3232 ptid_t ptid
= read_ptid (p
+ 1, &q
);
3237 if (p
[0] != ';' && p
[0] != 0)
3240 resume_info
[i
].thread
= ptid
;
3247 resume_info
[i
] = default_action
;
3249 resume (resume_info
, n
);
3254 write_enn (own_buf
);
3259 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
3262 resume (struct thread_resume
*actions
, size_t num_actions
)
3264 client_state
&cs
= get_client_state ();
3267 /* Check if among the threads that GDB wants actioned, there's
3268 one with a pending status to report. If so, skip actually
3269 resuming/stopping and report the pending event
3272 thread_info
*thread_with_status
= find_thread ([&] (thread_info
*thread
)
3274 return visit_actioned_threads (thread
, actions
, num_actions
,
3275 handle_pending_status
);
3278 if (thread_with_status
!= NULL
)
3284 the_target
->resume (actions
, num_actions
);
3287 write_ok (cs
.own_buf
);
3290 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
, 0, 1);
3292 if (cs
.last_status
.kind () == TARGET_WAITKIND_NO_RESUMED
3293 && !report_no_resumed
)
3295 /* The client does not support this stop reply. At least
3297 sprintf (cs
.own_buf
, "E.No unwaited-for children left.");
3298 disable_async_io ();
3302 if (cs
.last_status
.kind () != TARGET_WAITKIND_EXITED
3303 && cs
.last_status
.kind () != TARGET_WAITKIND_SIGNALLED
3304 && cs
.last_status
.kind () != TARGET_WAITKIND_THREAD_EXITED
3305 && cs
.last_status
.kind () != TARGET_WAITKIND_NO_RESUMED
)
3306 current_thread
->last_status
= cs
.last_status
;
3308 /* From the client's perspective, all-stop mode always stops all
3309 threads implicitly (and the target backend has already done
3310 so by now). Tag all threads as "want-stopped", so we don't
3311 resume them implicitly without the client telling us to. */
3312 gdb_wants_all_threads_stopped ();
3313 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, cs
.last_status
);
3314 disable_async_io ();
3316 if (cs
.last_status
.kind () == TARGET_WAITKIND_EXITED
3317 || cs
.last_status
.kind () == TARGET_WAITKIND_SIGNALLED
)
3318 target_mourn_inferior (cs
.last_ptid
);
3322 /* Attach to a new program. */
3324 handle_v_attach (char *own_buf
)
3326 client_state
&cs
= get_client_state ();
3328 int pid
= strtol (own_buf
+ 8, NULL
, 16);
3332 if (attach_inferior (pid
) == 0)
3334 /* Don't report shared library events after attaching, even if
3335 some libraries are preloaded. GDB will always poll the
3336 library list. Avoids the "stopped by shared library event"
3337 notice on the GDB side. */
3338 current_process ()->dlls_changed
= false;
3342 /* In non-stop, we don't send a resume reply. Stop events
3343 will follow up using the normal notification
3348 prepare_resume_reply (own_buf
, cs
.last_ptid
, cs
.last_status
);
3352 /* Not supported. */
3356 catch (const gdb_exception_error
&exception
)
3358 sprintf (own_buf
, "E.%s", exception
.what ());
3362 /* Decode an argument from the vRun packet buffer. PTR points to the
3363 first hex-encoded character in the buffer, and LEN is the number of
3364 characters to read from the packet buffer.
3366 If the argument decoding is successful, return a buffer containing the
3367 decoded argument, including a null terminator at the end.
3369 If the argument decoding fails for any reason, return nullptr. */
3371 static gdb::unique_xmalloc_ptr
<char>
3372 decode_v_run_arg (const char *ptr
, size_t len
)
3374 /* Two hex characters are required for each decoded byte. */
3378 /* The length in bytes needed for the decoded argument. */
3381 /* Buffer to decode the argument into. The '+ 1' is for the null
3382 terminator we will add. */
3383 char *arg
= (char *) xmalloc (len
+ 1);
3385 /* Decode the argument from the packet and add a null terminator. We do
3386 this within a try block as invalid characters within the PTR buffer
3387 will cause hex2bin to throw an exception. Our caller relies on us
3388 returning nullptr in order to clean up some memory allocations. */
3391 hex2bin (ptr
, (gdb_byte
*) arg
, len
);
3394 catch (const gdb_exception_error
&exception
)
3399 return gdb::unique_xmalloc_ptr
<char> (arg
);
3402 /* Run a new program. */
3404 handle_v_run (char *own_buf
)
3406 client_state
&cs
= get_client_state ();
3408 gdb::argv_vec new_argv
;
3409 gdb::unique_xmalloc_ptr
<char> new_program_name
;
3412 for (i
= 0, p
= own_buf
+ strlen ("vRun;");
3413 /* Exit condition is at the end of the loop. */;
3414 p
= next_p
+ 1, ++i
)
3416 next_p
= strchr (p
, ';');
3418 next_p
= p
+ strlen (p
);
3420 if (i
== 0 && p
== next_p
)
3422 /* No program specified. */
3423 gdb_assert (new_program_name
== nullptr);
3425 else if (p
== next_p
)
3427 /* Empty argument. */
3428 new_argv
.push_back (xstrdup (""));
3432 /* The length of the argument string in the packet. */
3433 size_t len
= next_p
- p
;
3435 gdb::unique_xmalloc_ptr
<char> arg
= decode_v_run_arg (p
, len
);
3438 write_enn (own_buf
);
3443 new_program_name
= std::move (arg
);
3445 new_argv
.push_back (arg
.release ());
3447 if (*next_p
== '\0')
3451 if (new_program_name
== nullptr)
3453 /* GDB didn't specify a program to run. Use the program from the
3454 last run with the new argument list. */
3455 if (program_path
.get () == nullptr)
3457 write_enn (own_buf
);
3462 program_path
.set (new_program_name
.get ());
3464 program_args
= construct_inferior_arguments (new_argv
.get ());
3468 target_create_inferior (program_path
.get (), program_args
);
3470 catch (const gdb_exception_error
&exception
)
3472 sprintf (own_buf
, "E.%s", exception
.what ());
3476 if (cs
.last_status
.kind () == TARGET_WAITKIND_STOPPED
)
3478 prepare_resume_reply (own_buf
, cs
.last_ptid
, cs
.last_status
);
3480 /* In non-stop, sending a resume reply doesn't set the general
3481 thread, but GDB assumes a vRun sets it (this is so GDB can
3482 query which is the main thread of the new inferior. */
3484 cs
.general_thread
= cs
.last_ptid
;
3487 write_enn (own_buf
);
3492 handle_v_kill (char *own_buf
)
3494 client_state
&cs
= get_client_state ();
3496 char *p
= &own_buf
[6];
3497 if (cs
.multi_process
)
3498 pid
= strtol (p
, NULL
, 16);
3502 process_info
*proc
= find_process_pid (pid
);
3504 if (proc
!= nullptr && kill_inferior (proc
) == 0)
3506 cs
.last_status
.set_signalled (GDB_SIGNAL_KILL
);
3507 cs
.last_ptid
= ptid_t (pid
);
3508 discard_queued_stop_replies (cs
.last_ptid
);
3512 write_enn (own_buf
);
3515 /* Handle all of the extended 'v' packets. */
3517 handle_v_requests (char *own_buf
, int packet_len
, int *new_packet_len
)
3519 client_state
&cs
= get_client_state ();
3520 if (!disable_packet_vCont
)
3522 if (strcmp (own_buf
, "vCtrlC") == 0)
3524 the_target
->request_interrupt ();
3529 if (startswith (own_buf
, "vCont;"))
3531 handle_v_cont (own_buf
);
3535 if (startswith (own_buf
, "vCont?"))
3537 strcpy (own_buf
, "vCont;c;C;t");
3539 if (target_supports_hardware_single_step ()
3540 || target_supports_software_single_step ()
3541 || !cs
.vCont_supported
)
3543 /* If target supports single step either by hardware or by
3544 software, add actions s and S to the list of supported
3545 actions. On the other hand, if GDB doesn't request the
3546 supported vCont actions in qSupported packet, add s and
3547 S to the list too. */
3548 own_buf
= own_buf
+ strlen (own_buf
);
3549 strcpy (own_buf
, ";s;S");
3552 if (target_supports_range_stepping ())
3554 own_buf
= own_buf
+ strlen (own_buf
);
3555 strcpy (own_buf
, ";r");
3561 if (startswith (own_buf
, "vFile:")
3562 && handle_vFile (own_buf
, packet_len
, new_packet_len
))
3565 if (startswith (own_buf
, "vAttach;"))
3567 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3569 fprintf (stderr
, "Already debugging a process\n");
3570 write_enn (own_buf
);
3573 handle_v_attach (own_buf
);
3577 if (startswith (own_buf
, "vRun;"))
3579 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3581 fprintf (stderr
, "Already debugging a process\n");
3582 write_enn (own_buf
);
3585 handle_v_run (own_buf
);
3589 if (startswith (own_buf
, "vKill;"))
3591 if (!target_running ())
3593 fprintf (stderr
, "No process to kill\n");
3594 write_enn (own_buf
);
3597 handle_v_kill (own_buf
);
3601 if (handle_notif_ack (own_buf
, packet_len
))
3604 /* Otherwise we didn't know what packet it was. Say we didn't
3610 /* Resume thread and wait for another event. In non-stop mode,
3611 don't really wait here, but return immediately to the event
3614 myresume (char *own_buf
, int step
, int sig
)
3616 client_state
&cs
= get_client_state ();
3617 struct thread_resume resume_info
[2];
3619 int valid_cont_thread
;
3621 valid_cont_thread
= (cs
.cont_thread
!= null_ptid
3622 && cs
.cont_thread
!= minus_one_ptid
);
3624 if (step
|| sig
|| valid_cont_thread
)
3626 resume_info
[0].thread
= current_thread
->id
;
3628 resume_info
[0].kind
= resume_step
;
3630 resume_info
[0].kind
= resume_continue
;
3631 resume_info
[0].sig
= sig
;
3635 if (!valid_cont_thread
)
3637 resume_info
[n
].thread
= minus_one_ptid
;
3638 resume_info
[n
].kind
= resume_continue
;
3639 resume_info
[n
].sig
= 0;
3643 resume (resume_info
, n
);
3646 /* Callback for for_each_thread. Make a new stop reply for each
3650 queue_stop_reply_callback (thread_info
*thread
)
3652 /* For now, assume targets that don't have this callback also don't
3653 manage the thread's last_status field. */
3654 if (!the_target
->supports_thread_stopped ())
3656 struct vstop_notif
*new_notif
= new struct vstop_notif
;
3658 new_notif
->ptid
= thread
->id
;
3659 new_notif
->status
= thread
->last_status
;
3660 /* Pass the last stop reply back to GDB, but don't notify
3662 notif_event_enque (¬if_stop
, new_notif
);
3666 if (target_thread_stopped (thread
))
3668 threads_debug_printf
3669 ("Reporting thread %s as already stopped with %s",
3670 target_pid_to_str (thread
->id
).c_str (),
3671 thread
->last_status
.to_string ().c_str ());
3673 gdb_assert (thread
->last_status
.kind () != TARGET_WAITKIND_IGNORE
);
3675 /* Pass the last stop reply back to GDB, but don't notify
3677 queue_stop_reply (thread
->id
, thread
->last_status
);
3682 /* Set this inferior threads's state as "want-stopped". We won't
3683 resume this thread until the client gives us another action for
3687 gdb_wants_thread_stopped (thread_info
*thread
)
3689 thread
->last_resume_kind
= resume_stop
;
3691 if (thread
->last_status
.kind () == TARGET_WAITKIND_IGNORE
)
3693 /* Most threads are stopped implicitly (all-stop); tag that with
3695 thread
->last_status
.set_stopped (GDB_SIGNAL_0
);
3699 /* Set all threads' states as "want-stopped". */
3702 gdb_wants_all_threads_stopped (void)
3704 for_each_thread (gdb_wants_thread_stopped
);
3707 /* Callback for for_each_thread. If the thread is stopped with an
3708 interesting event, mark it as having a pending event. */
3711 set_pending_status_callback (thread_info
*thread
)
3713 if (thread
->last_status
.kind () != TARGET_WAITKIND_STOPPED
3714 || (thread
->last_status
.sig () != GDB_SIGNAL_0
3715 /* A breakpoint, watchpoint or finished step from a previous
3716 GDB run isn't considered interesting for a new GDB run.
3717 If we left those pending, the new GDB could consider them
3718 random SIGTRAPs. This leaves out real async traps. We'd
3719 have to peek into the (target-specific) siginfo to
3720 distinguish those. */
3721 && thread
->last_status
.sig () != GDB_SIGNAL_TRAP
))
3722 thread
->status_pending_p
= 1;
3725 /* Status handler for the '?' packet. */
3728 handle_status (char *own_buf
)
3730 client_state
&cs
= get_client_state ();
3732 /* GDB is connected, don't forward events to the target anymore. */
3733 for_each_process ([] (process_info
*process
) {
3734 process
->gdb_detached
= 0;
3737 /* In non-stop mode, we must send a stop reply for each stopped
3738 thread. In all-stop mode, just send one for the first stopped
3743 for_each_thread (queue_stop_reply_callback
);
3745 /* The first is sent immediately. OK is sent if there is no
3746 stopped thread, which is the same handling of the vStopped
3747 packet (by design). */
3748 notif_write_event (¬if_stop
, cs
.own_buf
);
3752 thread_info
*thread
= NULL
;
3754 target_pause_all (false);
3755 target_stabilize_threads ();
3756 gdb_wants_all_threads_stopped ();
3758 /* We can only report one status, but we might be coming out of
3759 non-stop -- if more than one thread is stopped with
3760 interesting events, leave events for the threads we're not
3761 reporting now pending. They'll be reported the next time the
3762 threads are resumed. Start by marking all interesting events
3764 for_each_thread (set_pending_status_callback
);
3766 /* Prefer the last thread that reported an event to GDB (even if
3767 that was a GDB_SIGNAL_TRAP). */
3768 if (cs
.last_status
.kind () != TARGET_WAITKIND_IGNORE
3769 && cs
.last_status
.kind () != TARGET_WAITKIND_EXITED
3770 && cs
.last_status
.kind () != TARGET_WAITKIND_SIGNALLED
)
3771 thread
= find_thread_ptid (cs
.last_ptid
);
3773 /* If the last event thread is not found for some reason, look
3774 for some other thread that might have an event to report. */
3776 thread
= find_thread ([] (thread_info
*thr_arg
)
3778 return thr_arg
->status_pending_p
;
3781 /* If we're still out of luck, simply pick the first thread in
3784 thread
= get_first_thread ();
3788 thread_info
*tp
= (thread_info
*) thread
;
3790 /* We're reporting this event, so it's no longer
3792 tp
->status_pending_p
= 0;
3794 /* GDB assumes the current thread is the thread we're
3795 reporting the status for. */
3796 cs
.general_thread
= thread
->id
;
3797 set_desired_thread ();
3799 gdb_assert (tp
->last_status
.kind () != TARGET_WAITKIND_IGNORE
);
3800 prepare_resume_reply (own_buf
, tp
->id
, tp
->last_status
);
3803 strcpy (own_buf
, "W00");
3808 gdbserver_version (void)
3810 printf ("GNU gdbserver %s%s\n"
3811 "Copyright (C) 2024 Free Software Foundation, Inc.\n"
3812 "gdbserver is free software, covered by the "
3813 "GNU General Public License.\n"
3814 "This gdbserver was configured as \"%s\"\n",
3815 PKGVERSION
, version
, host_name
);
3819 gdbserver_usage (FILE *stream
)
3821 fprintf (stream
, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3822 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3823 "\tgdbserver [OPTIONS] --multi COMM\n"
3825 "COMM may either be a tty device (for serial debugging),\n"
3826 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3827 "stdin/stdout of gdbserver.\n"
3828 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3829 "PID is the process ID to attach to, when --attach is specified.\n"
3831 "Operating modes:\n"
3833 " --attach Attach to running process PID.\n"
3834 " --multi Start server without a specific program, and\n"
3835 " only quit when explicitly commanded.\n"
3836 " --once Exit after the first connection has closed.\n"
3837 " --help Print this message and then exit.\n"
3838 " --version Display version information and exit.\n"
3842 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3843 " --disable-randomization\n"
3844 " Run PROG with address space randomization disabled.\n"
3845 " --no-disable-randomization\n"
3846 " Don't disable address space randomization when\n"
3848 " --startup-with-shell\n"
3849 " Start PROG using a shell. I.e., execs a shell that\n"
3850 " then execs PROG. (default)\n"
3851 " --no-startup-with-shell\n"
3852 " Exec PROG directly instead of using a shell.\n"
3853 " Disables argument globbing and variable substitution\n"
3854 " on UNIX-like systems.\n"
3858 " --debug[=OPT1,OPT2,...]\n"
3859 " Enable debugging output.\n"
3861 " all, threads, event-loop, remote\n"
3862 " With no options, 'threads' is assumed.\n"
3863 " Prefix an option with '-' to disable\n"
3864 " debugging of that component.\n"
3865 " --debug-format=OPT1[,OPT2,...]\n"
3866 " Specify extra content in debugging output.\n"
3871 " --disable-packet=OPT1[,OPT2,...]\n"
3872 " Disable support for RSP packets or features.\n"
3874 " vCont, T, Tthread, qC, qfThreadInfo and \n"
3875 " threads (disable all threading packets).\n"
3877 "For more information, consult the GDB manual (available as on-line \n"
3878 "info or a printed manual).\n");
3879 if (REPORT_BUGS_TO
[0] && stream
== stdout
)
3880 fprintf (stream
, "Report bugs to \"%s\".\n", REPORT_BUGS_TO
);
3884 gdbserver_show_disableable (FILE *stream
)
3886 fprintf (stream
, "Disableable packets:\n"
3887 " vCont \tAll vCont packets\n"
3888 " qC \tQuerying the current thread\n"
3889 " qfThreadInfo\tThread listing\n"
3890 " Tthread \tPassing the thread specifier in the "
3891 "T stop reply packet\n"
3892 " threads \tAll of the above\n"
3893 " T \tAll 'T' packets\n");
3896 /* Start up the event loop. This is the entry point to the event
3902 /* Loop until there is nothing to do. This is the entry point to
3903 the event loop engine. If nothing is ready at this time, wait
3904 for something to happen (via wait_for_event), then process it.
3905 Return when there are no longer event sources to wait for. */
3907 keep_processing_events
= true;
3908 while (keep_processing_events
)
3910 /* Any events already waiting in the queue? */
3911 int res
= gdb_do_one_event ();
3913 /* Was there an error? */
3918 /* We are done with the event loop. There are no more event sources
3919 to listen to. So we exit gdbserver. */
3923 kill_inferior_callback (process_info
*process
)
3925 kill_inferior (process
);
3926 discard_queued_stop_replies (ptid_t (process
->pid
));
3929 /* Call this when exiting gdbserver with possible inferiors that need
3930 to be killed or detached from. */
3933 detach_or_kill_for_exit (void)
3935 /* First print a list of the inferiors we will be killing/detaching.
3936 This is to assist the user, for example, in case the inferior unexpectedly
3937 dies after we exit: did we screw up or did the inferior exit on its own?
3938 Having this info will save some head-scratching. */
3940 if (have_started_inferiors_p ())
3942 fprintf (stderr
, "Killing process(es):");
3944 for_each_process ([] (process_info
*process
) {
3945 if (!process
->attached
)
3946 fprintf (stderr
, " %d", process
->pid
);
3949 fprintf (stderr
, "\n");
3951 if (have_attached_inferiors_p ())
3953 fprintf (stderr
, "Detaching process(es):");
3955 for_each_process ([] (process_info
*process
) {
3956 if (process
->attached
)
3957 fprintf (stderr
, " %d", process
->pid
);
3960 fprintf (stderr
, "\n");
3963 /* Now we can kill or detach the inferiors. */
3964 for_each_process ([] (process_info
*process
) {
3965 int pid
= process
->pid
;
3967 if (process
->attached
)
3968 detach_inferior (process
);
3970 kill_inferior (process
);
3972 discard_queued_stop_replies (ptid_t (pid
));
3976 /* Value that will be passed to exit(3) when gdbserver exits. */
3977 static int exit_code
;
3979 /* Wrapper for detach_or_kill_for_exit that catches and prints
3983 detach_or_kill_for_exit_cleanup ()
3987 detach_or_kill_for_exit ();
3989 catch (const gdb_exception
&exception
)
3992 fprintf (stderr
, "Detach or kill failed: %s\n",
4000 namespace selftests
{
4003 test_memory_tagging_functions (void)
4005 /* Setup testing. */
4006 gdb::char_vector packet
;
4007 gdb::byte_vector tags
, bv
;
4008 std::string expected
;
4009 packet
.resize (32000);
4014 /* Test parsing a qMemTags request. */
4016 /* Valid request, addr, len and type updated. */
4020 strcpy (packet
.data (), "qMemTags:0,0:0");
4021 parse_fetch_memtags_request (packet
.data (), &addr
, &len
, &type
);
4022 SELF_CHECK (addr
== 0 && len
== 0 && type
== 0);
4024 /* Valid request, addr, len and type updated. */
4028 strcpy (packet
.data (), "qMemTags:deadbeef,ff:5");
4029 parse_fetch_memtags_request (packet
.data (), &addr
, &len
, &type
);
4030 SELF_CHECK (addr
== 0xdeadbeef && len
== 255 && type
== 5);
4032 /* Test creating a qMemTags reply. */
4034 /* Non-empty tag data. */
4037 for (int i
= 0; i
< 5; i
++)
4040 expected
= "m0001020304";
4041 SELF_CHECK (create_fetch_memtags_reply (packet
.data (), bv
) == true);
4042 SELF_CHECK (strcmp (packet
.data (), expected
.c_str ()) == 0);
4044 /* Test parsing a QMemTags request. */
4046 /* Valid request and empty tag data: addr, len, type and tags updated. */
4051 strcpy (packet
.data (), "QMemTags:0,0:0:");
4052 SELF_CHECK (parse_store_memtags_request (packet
.data (),
4053 &addr
, &len
, tags
, &type
) == true);
4054 SELF_CHECK (addr
== 0 && len
== 0 && type
== 0 && tags
.size () == 0);
4056 /* Valid request and non-empty tag data: addr, len, type
4057 and tags updated. */
4062 strcpy (packet
.data (),
4063 "QMemTags:deadbeef,ff:5:0001020304");
4064 SELF_CHECK (parse_store_memtags_request (packet
.data (), &addr
, &len
, tags
,
4066 SELF_CHECK (addr
== 0xdeadbeef && len
== 255 && type
== 5
4067 && tags
.size () == 5);
4070 } // namespace selftests
4071 #endif /* GDB_SELF_TEST */
4073 /* Main function. This is called by the real "main" function,
4074 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
4076 [[noreturn
]] static void
4077 captured_main (int argc
, char *argv
[])
4082 const char *port
= NULL
;
4083 char **next_arg
= &argv
[1];
4084 volatile int multi_mode
= 0;
4085 volatile int attach
= 0;
4087 bool selftest
= false;
4089 std::vector
<const char *> selftest_filters
;
4091 selftests::register_test ("remote_memory_tagging",
4092 selftests::test_memory_tagging_functions
);
4095 current_directory
= getcwd (NULL
, 0);
4096 client_state
&cs
= get_client_state ();
4098 if (current_directory
== NULL
)
4100 error (_("Could not find current working directory: %s"),
4101 safe_strerror (errno
));
4104 while (*next_arg
!= NULL
&& **next_arg
== '-')
4106 if (strcmp (*next_arg
, "--version") == 0)
4108 gdbserver_version ();
4111 else if (strcmp (*next_arg
, "--help") == 0)
4113 gdbserver_usage (stdout
);
4116 else if (strcmp (*next_arg
, "--attach") == 0)
4118 else if (strcmp (*next_arg
, "--multi") == 0)
4120 else if (strcmp (*next_arg
, "--wrapper") == 0)
4127 while (*next_arg
!= NULL
&& strcmp (*next_arg
, "--") != 0)
4129 wrapper_argv
+= *next_arg
;
4130 wrapper_argv
+= ' ';
4134 if (!wrapper_argv
.empty ())
4136 /* Erase the last whitespace. */
4137 wrapper_argv
.erase (wrapper_argv
.end () - 1);
4140 if (next_arg
== tmp
|| *next_arg
== NULL
)
4142 gdbserver_usage (stderr
);
4146 /* Consume the "--". */
4149 else if (startswith (*next_arg
, "--debug="))
4153 parse_debug_options ((*next_arg
) + sizeof ("--debug=") - 1);
4155 catch (const gdb_exception_error
&exception
)
4158 fprintf (stderr
, "gdbserver: %s\n", exception
.what ());
4162 else if (strcmp (*next_arg
, "--debug") == 0)
4166 parse_debug_options ("");
4168 catch (const gdb_exception_error
&exception
)
4171 fprintf (stderr
, "gdbserver: %s\n", exception
.what ());
4175 else if (startswith (*next_arg
, "--debug-format="))
4177 std::string error_msg
4178 = parse_debug_format_options ((*next_arg
)
4179 + sizeof ("--debug-format=") - 1, 0);
4181 if (!error_msg
.empty ())
4183 fprintf (stderr
, "%s", error_msg
.c_str ());
4187 else if (startswith (*next_arg
, "--debug-file="))
4188 debug_set_output ((*next_arg
) + sizeof ("--debug-file=") -1);
4189 else if (strcmp (*next_arg
, "--disable-packet") == 0)
4191 gdbserver_show_disableable (stdout
);
4194 else if (startswith (*next_arg
, "--disable-packet="))
4196 char *packets
= *next_arg
+= sizeof ("--disable-packet=") - 1;
4198 for (char *tok
= strtok_r (packets
, ",", &saveptr
);
4200 tok
= strtok_r (NULL
, ",", &saveptr
))
4202 if (strcmp ("vCont", tok
) == 0)
4203 disable_packet_vCont
= true;
4204 else if (strcmp ("Tthread", tok
) == 0)
4205 disable_packet_Tthread
= true;
4206 else if (strcmp ("qC", tok
) == 0)
4207 disable_packet_qC
= true;
4208 else if (strcmp ("qfThreadInfo", tok
) == 0)
4209 disable_packet_qfThreadInfo
= true;
4210 else if (strcmp ("T", tok
) == 0)
4211 disable_packet_T
= true;
4212 else if (strcmp ("threads", tok
) == 0)
4214 disable_packet_vCont
= true;
4215 disable_packet_Tthread
= true;
4216 disable_packet_qC
= true;
4217 disable_packet_qfThreadInfo
= true;
4221 fprintf (stderr
, "Don't know how to disable \"%s\".\n\n",
4223 gdbserver_show_disableable (stderr
);
4228 else if (strcmp (*next_arg
, "-") == 0)
4230 /* "-" specifies a stdio connection and is a form of port
4232 port
= STDIO_CONNECTION_NAME
;
4234 /* Implying --once here prevents a hang after stdin has been closed. */
4240 else if (strcmp (*next_arg
, "--disable-randomization") == 0)
4241 cs
.disable_randomization
= 1;
4242 else if (strcmp (*next_arg
, "--no-disable-randomization") == 0)
4243 cs
.disable_randomization
= 0;
4244 else if (strcmp (*next_arg
, "--startup-with-shell") == 0)
4245 startup_with_shell
= true;
4246 else if (strcmp (*next_arg
, "--no-startup-with-shell") == 0)
4247 startup_with_shell
= false;
4248 else if (strcmp (*next_arg
, "--once") == 0)
4250 else if (strcmp (*next_arg
, "--selftest") == 0)
4252 else if (startswith (*next_arg
, "--selftest="))
4257 const char *filter
= *next_arg
+ strlen ("--selftest=");
4258 if (*filter
== '\0')
4260 fprintf (stderr
, _("Error: selftest filter is empty.\n"));
4264 selftest_filters
.push_back (filter
);
4269 fprintf (stderr
, "Unknown argument: %s\n", *next_arg
);
4282 if ((port
== NULL
|| (!attach
&& !multi_mode
&& *next_arg
== NULL
))
4285 gdbserver_usage (stderr
);
4289 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
4290 opened by remote_prepare. */
4293 save_original_signals_state (false);
4295 /* We need to know whether the remote connection is stdio before
4296 starting the inferior. Inferiors created in this scenario have
4297 stdin,stdout redirected. So do this here before we call
4300 remote_prepare (port
);
4305 /* --attach used to come after PORT, so allow it there for
4307 if (*next_arg
!= NULL
&& strcmp (*next_arg
, "--attach") == 0)
4314 && (*next_arg
== NULL
4315 || (*next_arg
)[0] == '\0'
4316 || (pid
= strtoul (*next_arg
, &arg_end
, 0)) == 0
4318 || next_arg
[1] != NULL
))
4323 gdbserver_usage (stderr
);
4327 /* Gather information about the environment. */
4328 our_environ
= gdb_environ::from_host_environ ();
4330 initialize_async_io ();
4332 have_job_control ();
4333 if (target_supports_tracepoints ())
4334 initialize_tracepoint ();
4336 mem_buf
= (unsigned char *) xmalloc (PBUFSIZ
);
4341 selftests::run_tests (selftest_filters
);
4343 printf (_("Selftests have been disabled for this build.\n"));
4345 throw_quit ("Quit");
4348 if (pid
== 0 && *next_arg
!= NULL
)
4350 program_path
.set (next_arg
[0]);
4352 int n
= argc
- (next_arg
- argv
);
4354 = construct_inferior_arguments ({&next_arg
[1], &next_arg
[n
]});
4356 /* Wait till we are at first instruction in program. */
4357 target_create_inferior (program_path
.get (), program_args
);
4359 /* We are now (hopefully) stopped at the first instruction of
4360 the target process. This assumes that the target process was
4361 successfully created. */
4365 if (attach_inferior (pid
) == -1)
4366 error ("Attaching not supported on this target");
4368 /* Otherwise succeeded. */
4372 cs
.last_status
.set_exited (0);
4373 cs
.last_ptid
= minus_one_ptid
;
4376 SCOPE_EXIT
{ detach_or_kill_for_exit_cleanup (); };
4378 /* Don't report shared library events on the initial connection,
4379 even if some libraries are preloaded. Avoids the "stopped by
4380 shared library event" notice on gdb side. */
4381 if (current_thread
!= nullptr)
4382 current_process ()->dlls_changed
= false;
4384 if (cs
.last_status
.kind () == TARGET_WAITKIND_EXITED
4385 || cs
.last_status
.kind () == TARGET_WAITKIND_SIGNALLED
)
4390 if (!was_running
&& !multi_mode
)
4391 error ("No program to debug");
4396 cs
.multi_process
= 0;
4397 cs
.report_fork_events
= 0;
4398 cs
.report_vfork_events
= 0;
4399 cs
.report_exec_events
= 0;
4400 /* Be sure we're out of tfind mode. */
4401 cs
.current_traceframe
= -1;
4402 cs
.cont_thread
= null_ptid
;
4403 cs
.swbreak_feature
= 0;
4404 cs
.hwbreak_feature
= 0;
4405 cs
.vCont_supported
= 0;
4406 cs
.memory_tagging_feature
= false;
4407 cs
.error_message_supported
= false;
4413 /* Wait for events. This will return when all event sources
4414 are removed from the event loop. */
4415 start_event_loop ();
4417 /* If an exit was requested (using the "monitor exit"
4418 command), terminate now. */
4420 throw_quit ("Quit");
4422 /* The only other way to get here is for getpkt to fail:
4424 - If --once was specified, we're done.
4426 - If not in extended-remote mode, and we're no longer
4427 debugging anything, simply exit: GDB has disconnected
4428 after processing the last process exit.
4430 - Otherwise, close the connection and reopen it at the
4432 if (run_once
|| (!extended_protocol
&& !target_running ()))
4433 throw_quit ("Quit");
4436 "Remote side has terminated connection. "
4437 "GDBserver will reopen the connection.\n");
4439 /* Get rid of any pending statuses. An eventual reconnection
4440 (by the same GDB instance or another) will refresh all its
4441 state from scratch. */
4442 discard_queued_stop_replies (minus_one_ptid
);
4443 for_each_thread ([] (thread_info
*thread
)
4445 thread
->status_pending_p
= 0;
4450 if (disconnected_tracing
)
4452 /* Try to enable non-stop/async mode, so we we can
4453 both wait for an async socket accept, and handle
4454 async target events simultaneously. There's also
4455 no point either in having the target always stop
4456 all threads, when we're going to pass signals
4457 down without informing GDB. */
4460 if (the_target
->start_non_stop (true))
4463 /* Detaching implicitly resumes all threads;
4464 simply disconnecting does not. */
4470 "Disconnected tracing disabled; "
4471 "stopping trace run.\n");
4476 catch (const gdb_exception_error
&exception
)
4479 fprintf (stderr
, "gdbserver: %s\n", exception
.what ());
4481 if (response_needed
)
4483 write_enn (cs
.own_buf
);
4484 putpkt (cs
.own_buf
);
4488 throw_quit ("Quit");
4493 /* Main function. */
4496 main (int argc
, char *argv
[])
4498 setlocale (LC_CTYPE
, "");
4502 captured_main (argc
, argv
);
4504 catch (const gdb_exception
&exception
)
4506 if (exception
.reason
== RETURN_ERROR
)
4509 fprintf (stderr
, "%s\n", exception
.what ());
4510 fprintf (stderr
, "Exiting\n");
4517 gdb_assert_not_reached ("captured_main should never return");
4520 /* Process options coming from Z packets for a breakpoint. PACKET is
4521 the packet buffer. *PACKET is updated to point to the first char
4522 after the last processed option. */
4525 process_point_options (struct gdb_breakpoint
*bp
, const char **packet
)
4527 const char *dataptr
= *packet
;
4530 /* Check if data has the correct format. */
4531 if (*dataptr
!= ';')
4538 if (*dataptr
== ';')
4541 if (*dataptr
== 'X')
4543 /* Conditional expression. */
4544 threads_debug_printf ("Found breakpoint condition.");
4545 if (!add_breakpoint_condition (bp
, &dataptr
))
4546 dataptr
= strchrnul (dataptr
, ';');
4548 else if (startswith (dataptr
, "cmds:"))
4550 dataptr
+= strlen ("cmds:");
4551 threads_debug_printf ("Found breakpoint commands %s.", dataptr
);
4552 persist
= (*dataptr
== '1');
4554 if (add_breakpoint_commands (bp
, &dataptr
, persist
))
4555 dataptr
= strchrnul (dataptr
, ';');
4559 fprintf (stderr
, "Unknown token %c, ignoring.\n",
4561 /* Skip tokens until we find one that we recognize. */
4562 dataptr
= strchrnul (dataptr
, ';');
4568 /* Event loop callback that handles a serial event. The first byte in
4569 the serial buffer gets us here. We expect characters to arrive at
4570 a brisk pace, so we read the rest of the packet with a blocking
4574 process_serial_event (void)
4576 client_state
&cs
= get_client_state ();
4582 int new_packet_len
= -1;
4584 disable_async_io ();
4586 response_needed
= false;
4587 packet_len
= getpkt (cs
.own_buf
);
4588 if (packet_len
<= 0)
4591 /* Force an event loop break. */
4594 response_needed
= true;
4596 char ch
= cs
.own_buf
[0];
4600 handle_query (cs
.own_buf
, packet_len
, &new_packet_len
);
4603 handle_general_set (cs
.own_buf
);
4606 handle_detach (cs
.own_buf
);
4609 extended_protocol
= true;
4610 write_ok (cs
.own_buf
);
4613 handle_status (cs
.own_buf
);
4616 if (cs
.own_buf
[1] == 'c' || cs
.own_buf
[1] == 'g' || cs
.own_buf
[1] == 's')
4618 require_running_or_break (cs
.own_buf
);
4620 ptid_t thread_id
= read_ptid (&cs
.own_buf
[2], NULL
);
4622 if (thread_id
== null_ptid
|| thread_id
== minus_one_ptid
)
4623 thread_id
= null_ptid
;
4624 else if (thread_id
.is_pid ())
4626 /* The ptid represents a pid. */
4627 thread_info
*thread
= find_any_thread_of_pid (thread_id
.pid ());
4631 write_enn (cs
.own_buf
);
4635 thread_id
= thread
->id
;
4639 /* The ptid represents a lwp/tid. */
4640 if (find_thread_ptid (thread_id
) == NULL
)
4642 write_enn (cs
.own_buf
);
4647 if (cs
.own_buf
[1] == 'g')
4649 if (thread_id
== null_ptid
)
4651 /* GDB is telling us to choose any thread. Check if
4652 the currently selected thread is still valid. If
4653 it is not, select the first available. */
4654 thread_info
*thread
= find_thread_ptid (cs
.general_thread
);
4656 thread
= get_first_thread ();
4657 thread_id
= thread
->id
;
4660 cs
.general_thread
= thread_id
;
4661 set_desired_thread ();
4662 gdb_assert (current_thread
!= NULL
);
4664 else if (cs
.own_buf
[1] == 'c')
4665 cs
.cont_thread
= thread_id
;
4667 write_ok (cs
.own_buf
);
4671 /* Silently ignore it so that gdb can extend the protocol
4672 without compatibility headaches. */
4673 cs
.own_buf
[0] = '\0';
4677 require_running_or_break (cs
.own_buf
);
4678 if (cs
.current_traceframe
>= 0)
4680 regcache
a_regcache (current_target_desc ());
4682 if (fetch_traceframe_registers (cs
.current_traceframe
,
4683 &a_regcache
, -1) == 0)
4684 registers_to_string (&a_regcache
, cs
.own_buf
);
4686 write_enn (cs
.own_buf
);
4690 struct regcache
*regcache
;
4692 if (!set_desired_thread ())
4693 write_enn (cs
.own_buf
);
4696 regcache
= get_thread_regcache (current_thread
);
4697 registers_to_string (regcache
, cs
.own_buf
);
4702 require_running_or_break (cs
.own_buf
);
4703 if (cs
.current_traceframe
>= 0)
4704 write_enn (cs
.own_buf
);
4707 struct regcache
*regcache
;
4709 if (!set_desired_thread ())
4710 write_enn (cs
.own_buf
);
4713 regcache
= get_thread_regcache (current_thread
);
4714 registers_from_string (regcache
, &cs
.own_buf
[1]);
4715 write_ok (cs
.own_buf
);
4721 require_running_or_break (cs
.own_buf
);
4722 decode_m_packet (&cs
.own_buf
[1], &mem_addr
, &len
);
4723 int res
= gdb_read_memory (mem_addr
, mem_buf
, len
);
4725 write_enn (cs
.own_buf
);
4727 bin2hex (mem_buf
, cs
.own_buf
, res
);
4731 require_running_or_break (cs
.own_buf
);
4732 decode_M_packet (&cs
.own_buf
[1], &mem_addr
, &len
, &mem_buf
);
4733 if (gdb_write_memory (mem_addr
, mem_buf
, len
) == 0)
4734 write_ok (cs
.own_buf
);
4736 write_enn (cs
.own_buf
);
4740 require_running_or_break (cs
.own_buf
);
4741 decode_x_packet (&cs
.own_buf
[1], &mem_addr
, &len
);
4742 int res
= gdb_read_memory (mem_addr
, mem_buf
, len
);
4744 write_enn (cs
.own_buf
);
4747 gdb_byte
*buffer
= (gdb_byte
*) cs
.own_buf
;
4751 new_packet_len
= remote_escape_output (mem_buf
, res
, 1,
4755 new_packet_len
++; /* For the 'b' marker. */
4757 if (out_len_units
!= res
)
4759 write_enn (cs
.own_buf
);
4760 new_packet_len
= -1;
4763 suppress_next_putpkt_log ();
4768 require_running_or_break (cs
.own_buf
);
4769 if (decode_X_packet (&cs
.own_buf
[1], packet_len
- 1,
4770 &mem_addr
, &len
, &mem_buf
) < 0
4771 || gdb_write_memory (mem_addr
, mem_buf
, len
) != 0)
4772 write_enn (cs
.own_buf
);
4774 write_ok (cs
.own_buf
);
4777 require_running_or_break (cs
.own_buf
);
4778 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4779 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4780 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4783 myresume (cs
.own_buf
, 0, signal
);
4786 require_running_or_break (cs
.own_buf
);
4787 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4788 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4789 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4792 myresume (cs
.own_buf
, 1, signal
);
4795 require_running_or_break (cs
.own_buf
);
4797 myresume (cs
.own_buf
, 0, signal
);
4800 require_running_or_break (cs
.own_buf
);
4802 myresume (cs
.own_buf
, 1, signal
);
4804 case 'Z': /* insert_ ... */
4806 case 'z': /* remove_ ... */
4811 char type
= cs
.own_buf
[1];
4813 const int insert
= ch
== 'Z';
4814 const char *p
= &cs
.own_buf
[3];
4816 p
= unpack_varlen_hex (p
, &addr
);
4817 kind
= strtol (p
+ 1, &dataptr
, 16);
4821 struct gdb_breakpoint
*bp
;
4823 bp
= set_gdb_breakpoint (type
, addr
, kind
, &res
);
4828 /* GDB may have sent us a list of *point parameters to
4829 be evaluated on the target's side. Read such list
4830 here. If we already have a list of parameters, GDB
4831 is telling us to drop that list and use this one
4833 clear_breakpoint_conditions_and_commands (bp
);
4834 const char *options
= dataptr
;
4835 process_point_options (bp
, &options
);
4839 res
= delete_gdb_breakpoint (type
, addr
, kind
);
4842 write_ok (cs
.own_buf
);
4845 cs
.own_buf
[0] = '\0';
4847 write_enn (cs
.own_buf
);
4851 response_needed
= false;
4852 if (!target_running ())
4853 /* The packet we received doesn't make sense - but we can't
4854 reply to it, either. */
4857 fprintf (stderr
, "Killing all inferiors\n");
4859 for_each_process (kill_inferior_callback
);
4861 /* When using the extended protocol, we wait with no program
4862 running. The traditional protocol will exit instead. */
4863 if (extended_protocol
)
4865 cs
.last_status
.set_exited (GDB_SIGNAL_KILL
);
4873 require_running_or_break (cs
.own_buf
);
4875 ptid_t thread_id
= read_ptid (&cs
.own_buf
[1], NULL
);
4876 if (find_thread_ptid (thread_id
) == NULL
)
4878 write_enn (cs
.own_buf
);
4882 if (mythread_alive (thread_id
))
4883 write_ok (cs
.own_buf
);
4885 write_enn (cs
.own_buf
);
4889 response_needed
= false;
4891 /* Restarting the inferior is only supported in the extended
4893 if (extended_protocol
)
4895 if (target_running ())
4896 for_each_process (kill_inferior_callback
);
4898 fprintf (stderr
, "GDBserver restarting\n");
4900 /* Wait till we are at 1st instruction in prog. */
4901 if (program_path
.get () != NULL
)
4903 target_create_inferior (program_path
.get (), program_args
);
4905 if (cs
.last_status
.kind () == TARGET_WAITKIND_STOPPED
)
4907 /* Stopped at the first instruction of the target
4909 cs
.general_thread
= cs
.last_ptid
;
4913 /* Something went wrong. */
4914 cs
.general_thread
= null_ptid
;
4919 cs
.last_status
.set_exited (GDB_SIGNAL_KILL
);
4925 /* It is a request we don't understand. Respond with an
4926 empty packet so that gdb knows that we don't support this
4928 cs
.own_buf
[0] = '\0';
4932 /* Extended (long) request. */
4933 handle_v_requests (cs
.own_buf
, packet_len
, &new_packet_len
);
4937 /* It is a request we don't understand. Respond with an empty
4938 packet so that gdb knows that we don't support this
4940 cs
.own_buf
[0] = '\0';
4944 if (new_packet_len
!= -1)
4945 putpkt_binary (cs
.own_buf
, new_packet_len
);
4947 putpkt (cs
.own_buf
);
4949 response_needed
= false;
4957 /* Event-loop callback for serial events. */
4960 handle_serial_event (int err
, gdb_client_data client_data
)
4962 threads_debug_printf ("handling possible serial event");
4964 /* Really handle it. */
4965 if (process_serial_event () < 0)
4967 keep_processing_events
= false;
4971 /* Be sure to not change the selected thread behind GDB's back.
4972 Important in the non-stop mode asynchronous protocol. */
4973 set_desired_thread ();
4976 /* Push a stop notification on the notification queue. */
4979 push_stop_notification (ptid_t ptid
, const target_waitstatus
&status
)
4981 struct vstop_notif
*vstop_notif
= new struct vstop_notif
;
4983 vstop_notif
->status
= status
;
4984 vstop_notif
->ptid
= ptid
;
4985 /* Push Stop notification. */
4986 notif_push (¬if_stop
, vstop_notif
);
4989 /* Event-loop callback for target events. */
4992 handle_target_event (int err
, gdb_client_data client_data
)
4994 client_state
&cs
= get_client_state ();
4995 threads_debug_printf ("handling possible target event");
4997 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
,
5000 if (cs
.last_status
.kind () == TARGET_WAITKIND_NO_RESUMED
)
5002 if (gdb_connected () && report_no_resumed
)
5003 push_stop_notification (null_ptid
, cs
.last_status
);
5005 else if (cs
.last_status
.kind () != TARGET_WAITKIND_IGNORE
)
5007 int pid
= cs
.last_ptid
.pid ();
5008 struct process_info
*process
= find_process_pid (pid
);
5009 int forward_event
= !gdb_connected () || process
->gdb_detached
;
5011 if (cs
.last_status
.kind () == TARGET_WAITKIND_EXITED
5012 || cs
.last_status
.kind () == TARGET_WAITKIND_SIGNALLED
)
5014 mark_breakpoints_out (process
);
5015 target_mourn_inferior (cs
.last_ptid
);
5017 else if (cs
.last_status
.kind () == TARGET_WAITKIND_THREAD_EXITED
)
5021 /* We're reporting this thread as stopped. Update its
5022 "want-stopped" state to what the client wants, until it
5023 gets a new resume action. */
5024 current_thread
->last_resume_kind
= resume_stop
;
5025 current_thread
->last_status
= cs
.last_status
;
5030 if (!target_running ())
5032 /* The last process exited. We're done. */
5036 if (cs
.last_status
.kind () == TARGET_WAITKIND_EXITED
5037 || cs
.last_status
.kind () == TARGET_WAITKIND_SIGNALLED
5038 || cs
.last_status
.kind () == TARGET_WAITKIND_THREAD_EXITED
)
5042 /* A thread stopped with a signal, but gdb isn't
5043 connected to handle it. Pass it down to the
5044 inferior, as if it wasn't being traced. */
5045 enum gdb_signal signal
;
5047 threads_debug_printf ("GDB not connected; forwarding event %d for"
5049 (int) cs
.last_status
.kind (),
5050 target_pid_to_str (cs
.last_ptid
).c_str ());
5052 if (cs
.last_status
.kind () == TARGET_WAITKIND_STOPPED
)
5053 signal
= cs
.last_status
.sig ();
5055 signal
= GDB_SIGNAL_0
;
5056 target_continue (cs
.last_ptid
, signal
);
5061 push_stop_notification (cs
.last_ptid
, cs
.last_status
);
5063 if (cs
.last_status
.kind () == TARGET_WAITKIND_THREAD_EXITED
5064 && !target_any_resumed ())
5066 target_waitstatus ws
;
5067 ws
.set_no_resumed ();
5068 push_stop_notification (null_ptid
, ws
);
5073 /* Be sure to not change the selected thread behind GDB's back.
5074 Important in the non-stop mode asynchronous protocol. */
5075 set_desired_thread ();
5078 /* See gdbsupport/event-loop.h. */
5081 invoke_async_signal_handlers ()
5086 /* See gdbsupport/event-loop.h. */
5089 check_async_event_handlers ()
5094 /* See gdbsupport/errors.h */
5103 /* See gdbsupport/gdb_select.h. */
5106 gdb_select (int n
, fd_set
*readfds
, fd_set
*writefds
,
5107 fd_set
*exceptfds
, struct timeval
*timeout
)
5109 return select (n
, readfds
, writefds
, exceptfds
, timeout
);
5120 } // namespace selftests
5121 #endif /* GDB_SELF_TEST */