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"
54 /* PBUFSIZ must also be at least as big as IPA_CMD_BUF_SIZE, because
55 the client state data is passed directly to some agent
57 static_assert (PBUFSIZ
>= IPA_CMD_BUF_SIZE
);
59 #define require_running_or_return(BUF) \
60 if (!target_running ()) \
66 #define require_running_or_break(BUF) \
67 if (!target_running ()) \
73 /* The environment to pass to the inferior when creating it. */
75 static gdb_environ our_environ
;
79 static bool extended_protocol
;
80 static bool response_needed
;
81 static bool exit_requested
;
83 /* --once: Exit after the first connection has closed. */
86 /* Whether to report TARGET_WAITKIND_NO_RESUMED events. */
87 static bool report_no_resumed
;
89 /* The event loop checks this to decide whether to continue accepting
91 static bool keep_processing_events
= true;
96 /* Set the PROGRAM_PATH. Here we adjust the path of the provided
98 void set (const char *path
)
102 /* Make sure we're using the absolute path of the inferior when
104 if (!contains_dir_separator (m_path
.c_str ()))
108 /* Check if the file is in our CWD. If it is, then we prefix
109 its name with CURRENT_DIRECTORY. Otherwise, we leave the
110 name as-is because we'll try searching for it in $PATH. */
111 if (is_regular_file (m_path
.c_str (), ®_file_errno
))
112 m_path
= gdb_abspath (m_path
);
116 /* Return the PROGRAM_PATH. */
118 { return m_path
.empty () ? nullptr : m_path
.c_str (); }
121 /* The program name, adjusted if needed. */
124 static std::vector
<char *> program_args
;
125 static std::string wrapper_argv
;
127 /* The PID of the originally created or attached inferior. Used to
128 send signals to the process when GDB sends us an asynchronous interrupt
129 (user hitting Control-C in the client), and to wait for the child to exit
130 when no longer debugging it. */
132 unsigned long signal_pid
;
134 /* Set if you want to disable optional thread related packets support
135 in gdbserver, for the sake of testing GDB against stubs that don't
137 bool disable_packet_vCont
;
138 bool disable_packet_Tthread
;
139 bool disable_packet_qC
;
140 bool disable_packet_qfThreadInfo
;
141 bool disable_packet_T
;
143 static unsigned char *mem_buf
;
145 /* A sub-class of 'struct notif_event' for stop, holding information
146 relative to a single stop reply. We keep a queue of these to
147 push to GDB in non-stop mode. */
149 struct vstop_notif
: public notif_event
151 /* Thread or process that got the event. */
155 struct target_waitstatus status
;
158 /* The current btrace configuration. This is gdbserver's mirror of GDB's
159 btrace configuration. */
160 static struct btrace_config current_btrace_conf
;
162 /* The client remote protocol state. */
164 static client_state g_client_state
;
169 client_state
&cs
= g_client_state
;
174 /* Put a stop reply to the stop reply queue. */
177 queue_stop_reply (ptid_t ptid
, const target_waitstatus
&status
)
179 struct vstop_notif
*new_notif
= new struct vstop_notif
;
181 new_notif
->ptid
= ptid
;
182 new_notif
->status
= status
;
184 notif_event_enque (¬if_stop
, new_notif
);
188 remove_all_on_match_ptid (struct notif_event
*event
, ptid_t filter_ptid
)
190 struct vstop_notif
*vstop_event
= (struct vstop_notif
*) event
;
192 return vstop_event
->ptid
.matches (filter_ptid
);
198 discard_queued_stop_replies (ptid_t ptid
)
200 std::list
<notif_event
*>::iterator iter
, next
, end
;
201 end
= notif_stop
.queue
.end ();
202 for (iter
= notif_stop
.queue
.begin (); iter
!= end
; iter
= next
)
207 if (iter
== notif_stop
.queue
.begin ())
209 /* The head of the list contains the notification that was
210 already sent to GDB. So we can't remove it, otherwise
211 when GDB sends the vStopped, it would ack the _next_
212 notification, which hadn't been sent yet! */
216 if (remove_all_on_match_ptid (*iter
, ptid
))
219 notif_stop
.queue
.erase (iter
);
225 vstop_notif_reply (struct notif_event
*event
, char *own_buf
)
227 struct vstop_notif
*vstop
= (struct vstop_notif
*) event
;
229 prepare_resume_reply (own_buf
, vstop
->ptid
, vstop
->status
);
232 /* Helper for in_queued_stop_replies. */
235 in_queued_stop_replies_ptid (struct notif_event
*event
, ptid_t filter_ptid
)
237 struct vstop_notif
*vstop_event
= (struct vstop_notif
*) event
;
239 if (vstop_event
->ptid
.matches (filter_ptid
))
242 /* Don't resume fork children that GDB does not know about yet. */
243 if ((vstop_event
->status
.kind () == TARGET_WAITKIND_FORKED
244 || vstop_event
->status
.kind () == TARGET_WAITKIND_VFORKED
245 || vstop_event
->status
.kind () == TARGET_WAITKIND_THREAD_CLONED
)
246 && vstop_event
->status
.child_ptid ().matches (filter_ptid
))
255 in_queued_stop_replies (ptid_t ptid
)
257 for (notif_event
*event
: notif_stop
.queue
)
259 if (in_queued_stop_replies_ptid (event
, ptid
))
266 struct notif_server notif_stop
=
268 "vStopped", "Stop", {}, vstop_notif_reply
,
272 target_running (void)
274 return get_first_thread () != NULL
;
277 /* See gdbsupport/common-inferior.h. */
282 return !wrapper_argv
.empty () ? wrapper_argv
.c_str () : NULL
;
294 attach_inferior (int pid
)
296 client_state
&cs
= get_client_state ();
297 /* myattach should return -1 if attaching is unsupported,
298 0 if it succeeded, and call error() otherwise. */
300 if (find_process_pid (pid
) != nullptr)
301 error ("Already attached to process %d\n", pid
);
303 if (myattach (pid
) != 0)
306 fprintf (stderr
, "Attached; pid = %d\n", pid
);
309 /* FIXME - It may be that we should get the SIGNAL_PID from the
310 attach function, so that it can be the main thread instead of
311 whichever we were told to attach to. */
316 cs
.last_ptid
= mywait (ptid_t (pid
), &cs
.last_status
, 0, 0);
318 /* GDB knows to ignore the first SIGSTOP after attaching to a running
319 process using the "attach" command, but this is different; it's
320 just using "target remote". Pretend it's just starting up. */
321 if (cs
.last_status
.kind () == TARGET_WAITKIND_STOPPED
322 && cs
.last_status
.sig () == GDB_SIGNAL_STOP
)
323 cs
.last_status
.set_stopped (GDB_SIGNAL_TRAP
);
325 current_thread
->last_resume_kind
= resume_stop
;
326 current_thread
->last_status
= cs
.last_status
;
332 /* Decode a qXfer read request. Return 0 if everything looks OK,
336 decode_xfer_read (char *buf
, CORE_ADDR
*ofs
, unsigned int *len
)
338 /* After the read marker and annex, qXfer looks like a
339 traditional 'm' packet. */
340 decode_m_packet (buf
, ofs
, len
);
346 decode_xfer (char *buf
, char **object
, char **rw
, char **annex
, char **offset
)
348 /* Extract and NUL-terminate the object. */
350 while (*buf
&& *buf
!= ':')
356 /* Extract and NUL-terminate the read/write action. */
358 while (*buf
&& *buf
!= ':')
364 /* Extract and NUL-terminate the annex. */
366 while (*buf
&& *buf
!= ':')
376 /* Write the response to a successful qXfer read. Returns the
377 length of the (binary) data stored in BUF, corresponding
378 to as much of DATA/LEN as we could fit. IS_MORE controls
379 the first character of the response. */
381 write_qxfer_response (char *buf
, const gdb_byte
*data
, int len
, int is_more
)
390 return remote_escape_output (data
, len
, 1, (unsigned char *) buf
+ 1,
391 &out_len
, PBUFSIZ
- 2) + 1;
394 /* Handle btrace enabling in BTS format. */
397 handle_btrace_enable_bts (struct thread_info
*thread
)
399 if (thread
->btrace
!= NULL
)
400 error (_("Btrace already enabled."));
402 current_btrace_conf
.format
= BTRACE_FORMAT_BTS
;
403 thread
->btrace
= target_enable_btrace (thread
, ¤t_btrace_conf
);
406 /* Handle btrace enabling in Intel Processor Trace format. */
409 handle_btrace_enable_pt (struct thread_info
*thread
)
411 if (thread
->btrace
!= NULL
)
412 error (_("Btrace already enabled."));
414 current_btrace_conf
.format
= BTRACE_FORMAT_PT
;
415 thread
->btrace
= target_enable_btrace (thread
, ¤t_btrace_conf
);
418 /* Handle btrace disabling. */
421 handle_btrace_disable (struct thread_info
*thread
)
424 if (thread
->btrace
== NULL
)
425 error (_("Branch tracing not enabled."));
427 if (target_disable_btrace (thread
->btrace
) != 0)
428 error (_("Could not disable branch tracing."));
430 thread
->btrace
= NULL
;
433 /* Handle the "Qbtrace" packet. */
436 handle_btrace_general_set (char *own_buf
)
438 client_state
&cs
= get_client_state ();
439 struct thread_info
*thread
;
442 if (!startswith (own_buf
, "Qbtrace:"))
445 op
= own_buf
+ strlen ("Qbtrace:");
447 if (cs
.general_thread
== null_ptid
448 || cs
.general_thread
== minus_one_ptid
)
450 strcpy (own_buf
, "E.Must select a single thread.");
454 thread
= find_thread_ptid (cs
.general_thread
);
457 strcpy (own_buf
, "E.No such thread.");
463 if (strcmp (op
, "bts") == 0)
464 handle_btrace_enable_bts (thread
);
465 else if (strcmp (op
, "pt") == 0)
466 handle_btrace_enable_pt (thread
);
467 else if (strcmp (op
, "off") == 0)
468 handle_btrace_disable (thread
);
470 error (_("Bad Qbtrace operation. Use bts, pt, or off."));
474 catch (const gdb_exception_error
&exception
)
476 sprintf (own_buf
, "E.%s", exception
.what ());
482 /* Handle the "Qbtrace-conf" packet. */
485 handle_btrace_conf_general_set (char *own_buf
)
487 client_state
&cs
= get_client_state ();
488 struct thread_info
*thread
;
491 if (!startswith (own_buf
, "Qbtrace-conf:"))
494 op
= own_buf
+ strlen ("Qbtrace-conf:");
496 if (cs
.general_thread
== null_ptid
497 || cs
.general_thread
== minus_one_ptid
)
499 strcpy (own_buf
, "E.Must select a single thread.");
503 thread
= find_thread_ptid (cs
.general_thread
);
506 strcpy (own_buf
, "E.No such thread.");
510 if (startswith (op
, "bts:size="))
516 size
= strtoul (op
+ strlen ("bts:size="), &endp
, 16);
517 if (endp
== NULL
|| *endp
!= 0 || errno
!= 0 || size
> UINT_MAX
)
519 strcpy (own_buf
, "E.Bad size value.");
523 current_btrace_conf
.bts
.size
= (unsigned int) size
;
525 else if (strncmp (op
, "pt:size=", strlen ("pt:size=")) == 0)
531 size
= strtoul (op
+ strlen ("pt:size="), &endp
, 16);
532 if (endp
== NULL
|| *endp
!= 0 || errno
!= 0 || size
> UINT_MAX
)
534 strcpy (own_buf
, "E.Bad size value.");
538 current_btrace_conf
.pt
.size
= (unsigned int) size
;
540 else if (strncmp (op
, "pt:ptwrite=", strlen ("pt:ptwrite=")) == 0)
542 op
+= strlen ("pt:ptwrite=");
543 if (strncmp (op
, "\"yes\"", strlen ("\"yes\"")) == 0)
544 current_btrace_conf
.pt
.ptwrite
= true;
545 else if (strncmp (op
, "\"no\"", strlen ("\"no\"")) == 0)
546 current_btrace_conf
.pt
.ptwrite
= false;
549 strcpy (own_buf
, "E.Bad ptwrite value.");
553 else if (strncmp (op
, "pt:event-tracing=", strlen ("pt:event-tracing=")) == 0)
555 op
+= strlen ("pt:event-tracing=");
556 if (strncmp (op
, "\"yes\"", strlen ("\"yes\"")) == 0)
557 current_btrace_conf
.pt
.event_tracing
= true;
558 else if (strncmp (op
, "\"no\"", strlen ("\"no\"")) == 0)
559 current_btrace_conf
.pt
.event_tracing
= false;
562 strcpy (own_buf
, "E.Bad event-tracing value.");
568 strcpy (own_buf
, "E.Bad Qbtrace configuration option.");
576 /* Create the qMemTags packet reply given TAGS.
578 Returns true if parsing succeeded and false otherwise. */
581 create_fetch_memtags_reply (char *reply
, const gdb::byte_vector
&tags
)
583 /* It is an error to pass a zero-sized tag vector. */
584 gdb_assert (tags
.size () != 0);
586 std::string
packet ("m");
588 /* Write the tag data. */
589 packet
+= bin2hex (tags
.data (), tags
.size ());
591 /* Check if the reply is too big for the packet to handle. */
592 if (PBUFSIZ
< packet
.size ())
595 strcpy (reply
, packet
.c_str ());
599 /* Parse the QMemTags request into ADDR, LEN and TAGS.
601 Returns true if parsing succeeded and false otherwise. */
604 parse_store_memtags_request (char *request
, CORE_ADDR
*addr
, size_t *len
,
605 gdb::byte_vector
&tags
, int *type
)
607 gdb_assert (startswith (request
, "QMemTags:"));
609 const char *p
= request
+ strlen ("QMemTags:");
611 /* Read address and length. */
612 unsigned int length
= 0;
613 p
= decode_m_packet_params (p
, addr
, &length
, ':');
616 /* Read the tag type. */
617 ULONGEST tag_type
= 0;
618 p
= unpack_varlen_hex (p
, &tag_type
);
619 *type
= (int) tag_type
;
621 /* Make sure there is a colon after the type. */
625 /* Skip the colon. */
628 /* Read the tag data. */
634 /* Parse thread options starting at *P and return them. On exit,
635 advance *P past the options. */
637 static gdb_thread_options
638 parse_gdb_thread_options (const char **p
)
640 ULONGEST options
= 0;
641 *p
= unpack_varlen_hex (*p
, &options
);
642 return (gdb_thread_option
) options
;
645 /* Handle all of the extended 'Q' packets. */
648 handle_general_set (char *own_buf
)
650 client_state
&cs
= get_client_state ();
651 if (startswith (own_buf
, "QPassSignals:"))
653 int numsigs
= (int) GDB_SIGNAL_LAST
, i
;
654 const char *p
= own_buf
+ strlen ("QPassSignals:");
657 p
= decode_address_to_semicolon (&cursig
, p
);
658 for (i
= 0; i
< numsigs
; i
++)
662 cs
.pass_signals
[i
] = 1;
664 /* Keep looping, to clear the remaining signals. */
667 p
= decode_address_to_semicolon (&cursig
, p
);
670 cs
.pass_signals
[i
] = 0;
672 strcpy (own_buf
, "OK");
676 if (startswith (own_buf
, "QProgramSignals:"))
678 int numsigs
= (int) GDB_SIGNAL_LAST
, i
;
679 const char *p
= own_buf
+ strlen ("QProgramSignals:");
682 cs
.program_signals_p
= 1;
684 p
= decode_address_to_semicolon (&cursig
, p
);
685 for (i
= 0; i
< numsigs
; i
++)
689 cs
.program_signals
[i
] = 1;
691 /* Keep looping, to clear the remaining signals. */
694 p
= decode_address_to_semicolon (&cursig
, p
);
697 cs
.program_signals
[i
] = 0;
699 strcpy (own_buf
, "OK");
703 if (startswith (own_buf
, "QCatchSyscalls:"))
705 const char *p
= own_buf
+ sizeof ("QCatchSyscalls:") - 1;
708 struct process_info
*process
;
710 if (!target_running () || !target_supports_catch_syscall ())
716 if (strcmp (p
, "0") == 0)
718 else if (p
[0] == '1' && (p
[1] == ';' || p
[1] == '\0'))
722 fprintf (stderr
, "Unknown catch-syscalls mode requested: %s\n",
728 process
= current_process ();
729 process
->syscalls_to_catch
.clear ();
739 p
= decode_address_to_semicolon (&sysno
, p
);
740 process
->syscalls_to_catch
.push_back (sysno
);
744 process
->syscalls_to_catch
.push_back (ANY_SYSCALL
);
751 if (strcmp (own_buf
, "QEnvironmentReset") == 0)
753 our_environ
= gdb_environ::from_host_environ ();
759 if (startswith (own_buf
, "QEnvironmentHexEncoded:"))
761 const char *p
= own_buf
+ sizeof ("QEnvironmentHexEncoded:") - 1;
762 /* The final form of the environment variable. FINAL_VAR will
763 hold the 'VAR=VALUE' format. */
764 std::string final_var
= hex2str (p
);
765 std::string var_name
, var_value
;
767 remote_debug_printf ("[QEnvironmentHexEncoded received '%s']", p
);
768 remote_debug_printf ("[Environment variable to be set: '%s']",
771 size_t pos
= final_var
.find ('=');
772 if (pos
== std::string::npos
)
774 warning (_("Unexpected format for environment variable: '%s'"),
780 var_name
= final_var
.substr (0, pos
);
781 var_value
= final_var
.substr (pos
+ 1, std::string::npos
);
783 our_environ
.set (var_name
.c_str (), var_value
.c_str ());
789 if (startswith (own_buf
, "QEnvironmentUnset:"))
791 const char *p
= own_buf
+ sizeof ("QEnvironmentUnset:") - 1;
792 std::string varname
= hex2str (p
);
794 remote_debug_printf ("[QEnvironmentUnset received '%s']", p
);
795 remote_debug_printf ("[Environment variable to be unset: '%s']",
798 our_environ
.unset (varname
.c_str ());
804 if (strcmp (own_buf
, "QStartNoAckMode") == 0)
806 remote_debug_printf ("[noack mode enabled]");
813 if (startswith (own_buf
, "QNonStop:"))
815 char *mode
= own_buf
+ 9;
819 if (strcmp (mode
, "0") == 0)
821 else if (strcmp (mode
, "1") == 0)
825 /* We don't know what this mode is, so complain to
827 fprintf (stderr
, "Unknown non-stop mode requested: %s\n",
833 req_str
= req
? "non-stop" : "all-stop";
834 if (the_target
->start_non_stop (req
== 1) != 0)
836 fprintf (stderr
, "Setting %s mode failed\n", req_str
);
841 non_stop
= (req
!= 0);
843 remote_debug_printf ("[%s mode enabled]", req_str
);
849 if (startswith (own_buf
, "QDisableRandomization:"))
851 char *packet
= own_buf
+ strlen ("QDisableRandomization:");
854 unpack_varlen_hex (packet
, &setting
);
855 cs
.disable_randomization
= setting
;
857 remote_debug_printf (cs
.disable_randomization
858 ? "[address space randomization disabled]"
859 : "[address space randomization enabled]");
865 if (target_supports_tracepoints ()
866 && handle_tracepoint_general_set (own_buf
))
869 if (startswith (own_buf
, "QAgent:"))
871 char *mode
= own_buf
+ strlen ("QAgent:");
874 if (strcmp (mode
, "0") == 0)
876 else if (strcmp (mode
, "1") == 0)
880 /* We don't know what this value is, so complain to GDB. */
881 sprintf (own_buf
, "E.Unknown QAgent value");
885 /* Update the flag. */
887 remote_debug_printf ("[%s agent]", req
? "Enable" : "Disable");
892 if (handle_btrace_general_set (own_buf
))
895 if (handle_btrace_conf_general_set (own_buf
))
898 if (startswith (own_buf
, "QThreadEvents:"))
900 char *mode
= own_buf
+ strlen ("QThreadEvents:");
901 enum tribool req
= TRIBOOL_UNKNOWN
;
903 if (strcmp (mode
, "0") == 0)
905 else if (strcmp (mode
, "1") == 0)
909 /* We don't know what this mode is, so complain to GDB. */
911 = string_printf ("E.Unknown thread-events mode requested: %s\n",
913 strcpy (own_buf
, err
.c_str ());
917 cs
.report_thread_events
= (req
== TRIBOOL_TRUE
);
919 remote_debug_printf ("[thread events are now %s]\n",
920 cs
.report_thread_events
? "enabled" : "disabled");
926 if (startswith (own_buf
, "QThreadOptions;"))
928 const char *p
= own_buf
+ strlen ("QThreadOptions");
930 gdb_thread_options supported_options
= target_supported_thread_options ();
931 if (supported_options
== 0)
933 /* Something went wrong -- we don't support any option, but
934 GDB sent the packet anyway. */
939 /* We could store the options directly in thread->thread_options
940 without this map, but that would mean that a QThreadOptions
941 packet with a wildcard like "QThreadOptions;0;3:TID" would
942 result in the debug logs showing:
944 [options for TID are now 0x0]
945 [options for TID are now 0x3]
947 It's nicer if we only print the final options for each TID,
948 and if we only print about it if the options changed compared
949 to the options that were previously set on the thread. */
950 std::unordered_map
<thread_info
*, gdb_thread_options
> set_options
;
961 /* Read the options. */
963 gdb_thread_options options
= parse_gdb_thread_options (&p
);
965 if ((options
& ~supported_options
) != 0)
967 /* GDB asked for an unknown or unsupported option, so
970 = string_printf ("E.Unknown thread options requested: %s\n",
971 to_string (options
).c_str ());
972 strcpy (own_buf
, err
.c_str ());
978 if (p
[0] == ';' || p
[0] == '\0')
979 ptid
= minus_one_ptid
;
980 else if (p
[0] == ':')
984 ptid
= read_ptid (p
+ 1, &q
);
992 if (p
[0] != ';' && p
[0] != '\0')
1000 write_enn (own_buf
);
1004 /* Convert PID.-1 => PID.0 for ptid.matches. */
1005 if (ptid
.lwp () == -1)
1006 ptid
= ptid_t (ptid
.pid ());
1008 for_each_thread ([&] (thread_info
*thread
)
1010 if (thread
->id
.matches (ptid
))
1011 set_options
[thread
] = options
;
1015 for (const auto &iter
: set_options
)
1017 thread_info
*thread
= iter
.first
;
1018 gdb_thread_options options
= iter
.second
;
1020 if (thread
->thread_options
!= options
)
1022 threads_debug_printf ("[options for %s are now %s]\n",
1023 target_pid_to_str (thread
->id
).c_str (),
1024 to_string (options
).c_str ());
1026 thread
->thread_options
= options
;
1034 if (startswith (own_buf
, "QStartupWithShell:"))
1036 const char *value
= own_buf
+ strlen ("QStartupWithShell:");
1038 if (strcmp (value
, "1") == 0)
1039 startup_with_shell
= true;
1040 else if (strcmp (value
, "0") == 0)
1041 startup_with_shell
= false;
1044 /* Unknown value. */
1045 fprintf (stderr
, "Unknown value to startup-with-shell: %s\n",
1047 write_enn (own_buf
);
1051 remote_debug_printf ("[Inferior will %s started with shell]",
1052 startup_with_shell
? "be" : "not be");
1058 if (startswith (own_buf
, "QSetWorkingDir:"))
1060 const char *p
= own_buf
+ strlen ("QSetWorkingDir:");
1064 std::string path
= hex2str (p
);
1066 remote_debug_printf ("[Set the inferior's current directory to %s]",
1069 set_inferior_cwd (std::move (path
));
1073 /* An empty argument means that we should clear out any
1074 previously set cwd for the inferior. */
1075 set_inferior_cwd ("");
1077 remote_debug_printf ("[Unset the inferior's current directory; will "
1078 "use gdbserver's cwd]");
1086 /* Handle store memory tags packets. */
1087 if (startswith (own_buf
, "QMemTags:")
1088 && target_supports_memory_tagging ())
1090 gdb::byte_vector tags
;
1095 require_running_or_return (own_buf
);
1097 bool ret
= parse_store_memtags_request (own_buf
, &addr
, &len
, tags
,
1101 ret
= the_target
->store_memtags (addr
, len
, tags
, type
);
1104 write_enn (own_buf
);
1111 /* Otherwise we didn't know what packet it was. Say we didn't
1117 get_features_xml (const char *annex
)
1119 const struct target_desc
*desc
= current_target_desc ();
1121 /* `desc->xmltarget' defines what to return when looking for the
1122 "target.xml" file. Its contents can either be verbatim XML code
1123 (prefixed with a '@') or else the name of the actual XML file to
1124 be used in place of "target.xml".
1126 This variable is set up from the auto-generated
1127 init_registers_... routine for the current target. */
1129 if (strcmp (annex
, "target.xml") == 0)
1131 const char *ret
= tdesc_get_features_xml (desc
);
1143 /* Look for the annex. */
1144 for (i
= 0; xml_builtin
[i
][0] != NULL
; i
++)
1145 if (strcmp (annex
, xml_builtin
[i
][0]) == 0)
1148 if (xml_builtin
[i
][0] != NULL
)
1149 return xml_builtin
[i
][1];
1157 monitor_show_help (void)
1159 monitor_output ("The following monitor commands are supported:\n");
1160 monitor_output (" set debug on\n");
1161 monitor_output (" Enable general debugging messages\n");
1162 monitor_output (" set debug off\n");
1163 monitor_output (" Disable all debugging messages\n");
1164 monitor_output (" set debug COMPONENT <off|on>\n");
1165 monitor_output (" Enable debugging messages for COMPONENT, which is\n");
1166 monitor_output (" one of: all, threads, remote, event-loop.\n");
1167 monitor_output (" set debug-hw-points <0|1>\n");
1168 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
1169 monitor_output (" set debug-format option1[,option2,...]\n");
1170 monitor_output (" Add additional information to debugging messages\n");
1171 monitor_output (" Options: all, none, timestamp\n");
1172 monitor_output (" exit\n");
1173 monitor_output (" Quit GDBserver\n");
1176 /* Read trace frame or inferior memory. Returns the number of bytes
1177 actually read, zero when no further transfer is possible, and -1 on
1178 error. Return of a positive value smaller than LEN does not
1179 indicate there's no more to be read, only the end of the transfer.
1180 E.g., when GDB reads memory from a traceframe, a first request may
1181 be served from a memory block that does not cover the whole request
1182 length. A following request gets the rest served from either
1183 another block (of the same traceframe) or from the read-only
1187 gdb_read_memory (CORE_ADDR memaddr
, unsigned char *myaddr
, int len
)
1189 client_state
&cs
= get_client_state ();
1192 if (cs
.current_traceframe
>= 0)
1195 ULONGEST length
= len
;
1197 if (traceframe_read_mem (cs
.current_traceframe
,
1198 memaddr
, myaddr
, len
, &nbytes
))
1200 /* Data read from trace buffer, we're done. */
1203 if (!in_readonly_region (memaddr
, length
))
1205 /* Otherwise we have a valid readonly case, fall through. */
1206 /* (assume no half-trace half-real blocks for now) */
1209 if (set_desired_process ())
1210 res
= read_inferior_memory (memaddr
, myaddr
, len
);
1214 return res
== 0 ? len
: -1;
1217 /* Write trace frame or inferior memory. Actually, writing to trace
1218 frames is forbidden. */
1221 gdb_write_memory (CORE_ADDR memaddr
, const unsigned char *myaddr
, int len
)
1223 client_state
&cs
= get_client_state ();
1224 if (cs
.current_traceframe
>= 0)
1230 if (set_desired_process ())
1231 ret
= target_write_memory (memaddr
, myaddr
, len
);
1238 /* Handle qSearch:memory packets. */
1241 handle_search_memory (char *own_buf
, int packet_len
)
1243 CORE_ADDR start_addr
;
1244 CORE_ADDR search_space_len
;
1246 unsigned int pattern_len
;
1248 CORE_ADDR found_addr
;
1249 int cmd_name_len
= sizeof ("qSearch:memory:") - 1;
1251 pattern
= (gdb_byte
*) malloc (packet_len
);
1252 if (pattern
== NULL
)
1253 error ("Unable to allocate memory to perform the search");
1255 if (decode_search_memory_packet (own_buf
+ cmd_name_len
,
1256 packet_len
- cmd_name_len
,
1257 &start_addr
, &search_space_len
,
1258 pattern
, &pattern_len
) < 0)
1261 error ("Error in parsing qSearch:memory packet");
1264 auto read_memory
= [] (CORE_ADDR addr
, gdb_byte
*result
, size_t len
)
1266 return gdb_read_memory (addr
, result
, len
) == len
;
1269 found
= simple_search_memory (read_memory
, start_addr
, search_space_len
,
1270 pattern
, pattern_len
, &found_addr
);
1273 sprintf (own_buf
, "1,%lx", (long) found_addr
);
1274 else if (found
== 0)
1275 strcpy (own_buf
, "0");
1277 strcpy (own_buf
, "E00");
1282 /* Handle the "D" packet. */
1285 handle_detach (char *own_buf
)
1287 client_state
&cs
= get_client_state ();
1289 process_info
*process
;
1291 if (cs
.multi_process
)
1294 int pid
= strtol (&own_buf
[2], NULL
, 16);
1296 process
= find_process_pid (pid
);
1299 process
= current_process ();
1301 if (process
== NULL
)
1303 write_enn (own_buf
);
1307 if ((tracing
&& disconnected_tracing
) || any_persistent_commands (process
))
1309 if (tracing
&& disconnected_tracing
)
1311 "Disconnected tracing in effect, "
1312 "leaving gdbserver attached to the process\n");
1314 if (any_persistent_commands (process
))
1316 "Persistent commands are present, "
1317 "leaving gdbserver attached to the process\n");
1319 /* Make sure we're in non-stop/async mode, so we we can both
1320 wait for an async socket accept, and handle async target
1321 events simultaneously. There's also no point either in
1322 having the target stop all threads, when we're going to
1323 pass signals down without informing GDB. */
1326 threads_debug_printf ("Forcing non-stop mode");
1329 the_target
->start_non_stop (true);
1332 process
->gdb_detached
= 1;
1334 /* Detaching implicitly resumes all threads. */
1335 target_continue_no_signal (minus_one_ptid
);
1341 fprintf (stderr
, "Detaching from process %d\n", process
->pid
);
1344 /* We'll need this after PROCESS has been destroyed. */
1345 int pid
= process
->pid
;
1347 /* If this process has an unreported fork child, that child is not known to
1348 GDB, so GDB won't take care of detaching it. We must do it here.
1350 Here, we specifically don't want to use "safe iteration", as detaching
1351 another process might delete the next thread in the iteration, which is
1352 the one saved by the safe iterator. We will never delete the currently
1353 iterated on thread, so standard iteration should be safe. */
1354 for (thread_info
&thread
: process
->thread_list ())
1356 /* Only threads that have a pending fork event. */
1357 target_waitkind kind
;
1358 thread_info
*child
= target_thread_pending_child (&thread
, &kind
);
1359 if (child
== nullptr || kind
== TARGET_WAITKIND_THREAD_CLONED
)
1362 process_info
*fork_child_process
= child
->process ();
1363 int fork_child_pid
= fork_child_process
->pid
;
1365 if (detach_inferior (fork_child_process
) != 0)
1366 warning (_("Failed to detach fork child %s, child of %s"),
1367 target_pid_to_str (ptid_t (fork_child_pid
)).c_str (),
1368 target_pid_to_str (thread
.id
).c_str ());
1371 if (detach_inferior (process
) != 0)
1372 write_enn (own_buf
);
1375 discard_queued_stop_replies (ptid_t (pid
));
1378 if (extended_protocol
|| target_running ())
1380 /* There is still at least one inferior remaining or
1381 we are in extended mode, so don't terminate gdbserver,
1382 and instead treat this like a normal program exit. */
1383 cs
.last_status
.set_exited (0);
1384 cs
.last_ptid
= ptid_t (pid
);
1386 switch_to_thread (nullptr);
1393 /* If we are attached, then we can exit. Otherwise, we
1394 need to hang around doing nothing, until the child is
1396 join_inferior (pid
);
1402 /* Parse options to --debug-format= and "monitor set debug-format".
1403 ARG is the text after "--debug-format=" or "monitor set debug-format".
1404 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1405 This triggers calls to monitor_output.
1406 The result is an empty string if all options were parsed ok, otherwise an
1407 error message which the caller must free.
1409 N.B. These commands affect all debug format settings, they are not
1410 cumulative. If a format is not specified, it is turned off.
1411 However, we don't go to extra trouble with things like
1412 "monitor set debug-format all,none,timestamp".
1413 Instead we just parse them one at a time, in order.
1415 The syntax for "monitor set debug" we support here is not identical
1416 to gdb's "set debug foo on|off" because we also use this function to
1417 parse "--debug-format=foo,bar". */
1420 parse_debug_format_options (const char *arg
, int is_monitor
)
1422 /* First turn all debug format options off. */
1423 debug_timestamp
= 0;
1425 /* First remove leading spaces, for "monitor set debug-format". */
1426 while (isspace (*arg
))
1429 std::vector
<gdb::unique_xmalloc_ptr
<char>> options
1430 = delim_string_to_char_ptr_vec (arg
, ',');
1432 for (const gdb::unique_xmalloc_ptr
<char> &option
: options
)
1434 if (strcmp (option
.get (), "all") == 0)
1436 debug_timestamp
= 1;
1438 monitor_output ("All extra debug format options enabled.\n");
1440 else if (strcmp (option
.get (), "none") == 0)
1442 debug_timestamp
= 0;
1444 monitor_output ("All extra debug format options disabled.\n");
1446 else if (strcmp (option
.get (), "timestamp") == 0)
1448 debug_timestamp
= 1;
1450 monitor_output ("Timestamps will be added to debug output.\n");
1452 else if (*option
== '\0')
1454 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1458 return string_printf ("Unknown debug-format argument: \"%s\"\n",
1462 return std::string ();
1465 /* A wrapper to enable, or disable a debug flag. These are debug flags
1466 that control the debug output from gdbserver, that developers might
1467 want, this is not something most end users will need. */
1471 /* NAME is the name of this debug option, this should be a simple string
1472 containing no whitespace, starting with a letter from isalpha(), and
1473 contain only isalnum() characters and '_' underscore and '-' hyphen.
1475 SETTER is a callback function used to set the debug variable. This
1476 callback will be passed true to enable the debug setting, or false to
1477 disable the debug setting. */
1478 debug_opt (const char *name
, std::function
<void (bool)> setter
)
1482 gdb_assert (isalpha (*name
));
1485 /* Called to enable or disable the debug setting. */
1486 void set (bool enable
) const
1491 /* Return the name of this debug option. */
1492 const char *name () const
1496 /* The name of this debug option. */
1499 /* The callback to update the debug setting. */
1500 std::function
<void (bool)> m_setter
;
1503 /* The set of all debug options that gdbserver supports. These are the
1504 options that can be passed to the command line '--debug=...' flag, or to
1505 the monitor command 'monitor set debug ...'. */
1507 static std::vector
<debug_opt
> all_debug_opt
{
1508 {"threads", [] (bool enable
)
1510 debug_threads
= enable
;
1512 {"remote", [] (bool enable
)
1514 remote_debug
= enable
;
1516 {"event-loop", [] (bool enable
)
1518 debug_event_loop
= (enable
? debug_event_loop_kind::ALL
1519 : debug_event_loop_kind::OFF
);
1523 /* Parse the options to --debug=...
1525 OPTIONS is the string of debug components which should be enabled (or
1526 disabled), and must not be nullptr. An empty OPTIONS string is valid,
1527 in which case a default set of debug components will be enabled.
1529 An unknown, or otherwise invalid debug component will result in an
1530 exception being thrown.
1532 OPTIONS can consist of multiple debug component names separated by a
1533 comma. Debugging for each component will be turned on. The special
1534 component 'all' can be used to enable debugging for all components.
1536 A component can also be prefixed with '-' to disable debugging of that
1537 component, so a user might use: '--debug=all,-remote', to enable all
1538 debugging, except for the remote (protocol) component. Components are
1539 processed left to write in the OPTIONS list. */
1542 parse_debug_options (const char *options
)
1544 gdb_assert (options
!= nullptr);
1546 /* Empty options means the "default" set. This exists mostly for
1547 backwards compatibility with gdbserver's legacy behaviour. */
1548 if (*options
== '\0')
1549 options
= "+threads";
1551 while (*options
!= '\0')
1553 const char *end
= strchrnul (options
, ',');
1555 bool enable
= *options
!= '-';
1556 if (*options
== '-' || *options
== '+')
1559 std::string
opt (options
, end
- options
);
1561 if (opt
.size () == 0)
1562 error ("invalid empty debug option");
1564 bool is_opt_all
= opt
== "all";
1567 for (const auto &debug_opt
: all_debug_opt
)
1568 if (is_opt_all
|| opt
== debug_opt
.name ())
1570 debug_opt
.set (enable
);
1577 error ("unknown debug option '%s'", opt
.c_str ());
1579 options
= (*end
== ',') ? end
+ 1 : end
;
1583 /* Called from the 'monitor' command handler, to handle general 'set debug'
1584 monitor commands with one of the formats:
1586 set debug COMPONENT VALUE
1589 In both of these command formats VALUE can be 'on', 'off', '1', or '0'
1590 with 1/0 being equivalent to on/off respectively.
1592 In the no-COMPONENT version of the command, if VALUE is 'on' (or '1')
1593 then the component 'threads' is assumed, this is for backward
1594 compatibility, but maybe in the future we might find a better "default"
1595 set of debug flags to enable.
1597 In the no-COMPONENT version of the command, if VALUE is 'off' (or '0')
1598 then all debugging is turned off.
1600 Otherwise, COMPONENT must be one of the known debug components, and that
1601 component is either enabled or disabled as appropriate.
1603 The string MON contains either 'COMPONENT VALUE' or just the 'VALUE' for
1604 the second command format, the 'set debug ' has been stripped off
1607 Return a string containing an error message if something goes wrong,
1608 this error can be returned as part of the monitor command output. If
1609 everything goes correctly then the debug global will have been updated,
1610 and an empty string is returned. */
1613 handle_general_monitor_debug (const char *mon
)
1615 mon
= skip_spaces (mon
);
1618 return "No debug component name found.\n";
1620 /* Find the first word within MON. This is either the component name,
1621 or the value if no component has been given. */
1622 const char *end
= skip_to_space (mon
);
1623 std::string
component (mon
, end
- mon
);
1624 if (component
.find (',') != component
.npos
|| component
[0] == '-'
1625 || component
[0] == '+')
1626 return "Invalid character found in debug component name.\n";
1628 /* In ACTION_STR we create a string that will be passed to the
1629 parse_debug_options string. This will be either '+COMPONENT' or
1630 '-COMPONENT' depending on whether we want to enable or disable
1632 std::string action_str
;
1634 /* If parse_debug_options succeeds, then MSG will be returned to the user
1635 as the output of the monitor command. */
1638 /* Check for 'set debug off', this disables all debug output. */
1639 if (component
== "0" || component
== "off")
1641 if (*skip_spaces (end
) != '\0')
1642 return string_printf
1643 ("Junk '%s' found at end of 'set debug %s' command.\n",
1644 skip_spaces (end
), std::string (mon
, end
- mon
).c_str ());
1646 action_str
= "-all";
1647 msg
= "All debug output disabled.\n";
1649 /* Check for 'set debug on', this disables a general set of debug. */
1650 else if (component
== "1" || component
== "on")
1652 if (*skip_spaces (end
) != '\0')
1653 return string_printf
1654 ("Junk '%s' found at end of 'set debug %s' command.\n",
1655 skip_spaces (end
), std::string (mon
, end
- mon
).c_str ());
1657 action_str
= "+threads";
1658 msg
= "General debug output enabled.\n";
1660 /* Otherwise we should have 'set debug COMPONENT VALUE'. Extract the two
1661 parts and validate. */
1664 /* Figure out the value the user passed. */
1665 const char *value_start
= skip_spaces (end
);
1666 if (*value_start
== '\0')
1667 return string_printf ("Missing value for 'set debug %s' command.\n",
1670 const char *after_value
= skip_to_space (value_start
);
1671 if (*skip_spaces (after_value
) != '\0')
1672 return string_printf
1673 ("Junk '%s' found at end of 'set debug %s' command.\n",
1674 skip_spaces (after_value
),
1675 std::string (mon
, after_value
- mon
).c_str ());
1677 std::string
value (value_start
, after_value
- value_start
);
1679 /* Check VALUE to see if we are enabling, or disabling. */
1681 if (value
== "0" || value
== "off")
1683 else if (value
== "1" || value
== "on")
1686 return string_printf ("Invalid value '%s' for 'set debug %s'.\n",
1688 std::string (mon
, end
- mon
).c_str ());
1690 action_str
= std::string (enable
? "+" : "-") + component
;
1691 msg
= string_printf ("Debug output for '%s' %s.\n", component
.c_str (),
1692 enable
? "enabled" : "disabled");
1695 gdb_assert (!msg
.empty ());
1696 gdb_assert (!action_str
.empty ());
1700 parse_debug_options (action_str
.c_str ());
1701 monitor_output (msg
.c_str ());
1703 catch (const gdb_exception_error
&exception
)
1705 return string_printf ("Error: %s\n", exception
.what ());
1711 /* Handle monitor commands not handled by target-specific handlers. */
1714 handle_monitor_command (char *mon
, char *own_buf
)
1716 if (startswith (mon
, "set debug "))
1718 std::string error_msg
1719 = handle_general_monitor_debug (mon
+ sizeof ("set debug ") - 1);
1721 if (!error_msg
.empty ())
1723 monitor_output (error_msg
.c_str ());
1724 monitor_show_help ();
1725 write_enn (own_buf
);
1728 else if (strcmp (mon
, "set debug-hw-points 1") == 0)
1730 show_debug_regs
= 1;
1731 monitor_output ("H/W point debugging output enabled.\n");
1733 else if (strcmp (mon
, "set debug-hw-points 0") == 0)
1735 show_debug_regs
= 0;
1736 monitor_output ("H/W point debugging output disabled.\n");
1738 else if (startswith (mon
, "set debug-format "))
1740 std::string error_msg
1741 = parse_debug_format_options (mon
+ sizeof ("set debug-format ") - 1,
1744 if (!error_msg
.empty ())
1746 monitor_output (error_msg
.c_str ());
1747 monitor_show_help ();
1748 write_enn (own_buf
);
1751 else if (strcmp (mon
, "set debug-file") == 0)
1752 debug_set_output (nullptr);
1753 else if (startswith (mon
, "set debug-file "))
1754 debug_set_output (mon
+ sizeof ("set debug-file ") - 1);
1755 else if (strcmp (mon
, "help") == 0)
1756 monitor_show_help ();
1757 else if (strcmp (mon
, "exit") == 0)
1758 exit_requested
= true;
1761 monitor_output ("Unknown monitor command.\n\n");
1762 monitor_show_help ();
1763 write_enn (own_buf
);
1767 /* Associates a callback with each supported qXfer'able object. */
1771 /* The object this handler handles. */
1774 /* Request that the target transfer up to LEN 8-bit bytes of the
1775 target's OBJECT. The OFFSET, for a seekable object, specifies
1776 the starting point. The ANNEX can be used to provide additional
1777 data-specific information to the target.
1779 Return the number of bytes actually transferred, zero when no
1780 further transfer is possible, -1 on error, -2 when the transfer
1781 is not supported, and -3 on a verbose error message that should
1782 be preserved. Return of a positive value smaller than LEN does
1783 not indicate the end of the object, only the end of the transfer.
1785 One, and only one, of readbuf or writebuf must be non-NULL. */
1786 int (*xfer
) (const char *annex
,
1787 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1788 ULONGEST offset
, LONGEST len
);
1791 /* Handle qXfer:auxv:read. */
1794 handle_qxfer_auxv (const char *annex
,
1795 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1796 ULONGEST offset
, LONGEST len
)
1798 if (!the_target
->supports_read_auxv () || writebuf
!= NULL
)
1801 if (annex
[0] != '\0' || current_thread
== NULL
)
1804 return the_target
->read_auxv (current_thread
->id
.pid (), offset
, readbuf
,
1808 /* Handle qXfer:exec-file:read. */
1811 handle_qxfer_exec_file (const char *annex
,
1812 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1813 ULONGEST offset
, LONGEST len
)
1818 if (!the_target
->supports_pid_to_exec_file () || writebuf
!= NULL
)
1821 if (annex
[0] == '\0')
1823 if (current_thread
== NULL
)
1826 pid
= current_thread
->id
.pid ();
1830 annex
= unpack_varlen_hex (annex
, &pid
);
1831 if (annex
[0] != '\0')
1838 const char *file
= the_target
->pid_to_exec_file (pid
);
1842 total_len
= strlen (file
);
1844 if (offset
> total_len
)
1847 if (offset
+ len
> total_len
)
1848 len
= total_len
- offset
;
1850 memcpy (readbuf
, file
+ offset
, len
);
1854 /* Handle qXfer:features:read. */
1857 handle_qxfer_features (const char *annex
,
1858 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1859 ULONGEST offset
, LONGEST len
)
1861 const char *document
;
1864 if (writebuf
!= NULL
)
1867 if (!target_running ())
1870 /* Grab the correct annex. */
1871 document
= get_features_xml (annex
);
1872 if (document
== NULL
)
1875 total_len
= strlen (document
);
1877 if (offset
> total_len
)
1880 if (offset
+ len
> total_len
)
1881 len
= total_len
- offset
;
1883 memcpy (readbuf
, document
+ offset
, len
);
1887 /* Handle qXfer:libraries:read. */
1890 handle_qxfer_libraries (const char *annex
,
1891 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1892 ULONGEST offset
, LONGEST len
)
1894 if (writebuf
!= NULL
)
1897 if (annex
[0] != '\0' || current_thread
== NULL
)
1900 std::string document
= "<library-list version=\"1.0\">\n";
1902 process_info
*proc
= current_process ();
1903 for (const dll_info
&dll
: proc
->all_dlls
)
1904 document
+= string_printf
1905 (" <library name=\"%s\"><segment address=\"0x%s\"/></library>\n",
1906 dll
.name
.c_str (), paddress (dll
.base_addr
));
1908 document
+= "</library-list>\n";
1910 if (offset
> document
.length ())
1913 if (offset
+ len
> document
.length ())
1914 len
= document
.length () - offset
;
1916 memcpy (readbuf
, &document
[offset
], len
);
1921 /* Handle qXfer:libraries-svr4:read. */
1924 handle_qxfer_libraries_svr4 (const char *annex
,
1925 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1926 ULONGEST offset
, LONGEST len
)
1928 if (writebuf
!= NULL
)
1931 if (current_thread
== NULL
1932 || !the_target
->supports_qxfer_libraries_svr4 ())
1935 return the_target
->qxfer_libraries_svr4 (annex
, readbuf
, writebuf
,
1939 /* Handle qXfer:osadata:read. */
1942 handle_qxfer_osdata (const char *annex
,
1943 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1944 ULONGEST offset
, LONGEST len
)
1946 if (!the_target
->supports_qxfer_osdata () || writebuf
!= NULL
)
1949 return the_target
->qxfer_osdata (annex
, readbuf
, NULL
, offset
, len
);
1952 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1955 handle_qxfer_siginfo (const char *annex
,
1956 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1957 ULONGEST offset
, LONGEST len
)
1959 if (!the_target
->supports_qxfer_siginfo ())
1962 if (annex
[0] != '\0' || current_thread
== NULL
)
1965 return the_target
->qxfer_siginfo (annex
, readbuf
, writebuf
, offset
, len
);
1968 /* Handle qXfer:statictrace:read. */
1971 handle_qxfer_statictrace (const char *annex
,
1972 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1973 ULONGEST offset
, LONGEST len
)
1975 client_state
&cs
= get_client_state ();
1978 if (writebuf
!= NULL
)
1981 if (annex
[0] != '\0' || current_thread
== NULL
1982 || cs
.current_traceframe
== -1)
1985 if (traceframe_read_sdata (cs
.current_traceframe
, offset
,
1986 readbuf
, len
, &nbytes
))
1991 /* Helper for handle_qxfer_threads_proper.
1992 Emit the XML to describe the thread of INF. */
1995 handle_qxfer_threads_worker (thread_info
*thread
, std::string
*buffer
)
1997 ptid_t ptid
= thread
->id
;
1999 int core
= target_core_of_thread (ptid
);
2001 const char *name
= target_thread_name (ptid
);
2004 bool handle_status
= target_thread_handle (ptid
, &handle
, &handle_len
);
2006 /* If this is a (v)fork/clone child (has a (v)fork/clone parent),
2007 GDB does not yet know about this thread, and must not know about
2008 it until it gets the corresponding (v)fork/clone event. Exclude
2009 this thread from the list. */
2010 if (target_thread_pending_parent (thread
) != nullptr)
2013 write_ptid (ptid_s
, ptid
);
2015 string_xml_appendf (*buffer
, "<thread id=\"%s\"", ptid_s
);
2019 sprintf (core_s
, "%d", core
);
2020 string_xml_appendf (*buffer
, " core=\"%s\"", core_s
);
2024 string_xml_appendf (*buffer
, " name=\"%s\"", name
);
2028 char *handle_s
= (char *) alloca (handle_len
* 2 + 1);
2029 bin2hex (handle
, handle_s
, handle_len
);
2030 string_xml_appendf (*buffer
, " handle=\"%s\"", handle_s
);
2033 string_xml_appendf (*buffer
, "/>\n");
2036 /* Helper for handle_qxfer_threads. Return true on success, false
2040 handle_qxfer_threads_proper (std::string
*buffer
)
2042 *buffer
+= "<threads>\n";
2044 /* The target may need to access memory and registers (e.g. via
2045 libthread_db) to fetch thread properties. Even if don't need to
2046 stop threads to access memory, we still will need to be able to
2047 access registers, and other ptrace accesses like
2048 PTRACE_GET_THREAD_AREA that require a paused thread. Pause all
2049 threads here, so that we pause each thread at most once for all
2052 target_pause_all (true);
2054 for_each_thread ([&] (thread_info
*thread
)
2056 handle_qxfer_threads_worker (thread
, buffer
);
2060 target_unpause_all (true);
2062 *buffer
+= "</threads>\n";
2066 /* Handle qXfer:threads:read. */
2069 handle_qxfer_threads (const char *annex
,
2070 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2071 ULONGEST offset
, LONGEST len
)
2073 static std::string result
;
2075 if (writebuf
!= NULL
)
2078 if (annex
[0] != '\0')
2083 /* When asked for data at offset 0, generate everything and store into
2084 'result'. Successive reads will be served off 'result'. */
2087 bool res
= handle_qxfer_threads_proper (&result
);
2093 if (offset
>= result
.length ())
2095 /* We're out of data. */
2100 if (len
> result
.length () - offset
)
2101 len
= result
.length () - offset
;
2103 memcpy (readbuf
, result
.c_str () + offset
, len
);
2108 /* Handle qXfer:traceframe-info:read. */
2111 handle_qxfer_traceframe_info (const char *annex
,
2112 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2113 ULONGEST offset
, LONGEST len
)
2115 client_state
&cs
= get_client_state ();
2116 static std::string result
;
2118 if (writebuf
!= NULL
)
2121 if (!target_running () || annex
[0] != '\0' || cs
.current_traceframe
== -1)
2126 /* When asked for data at offset 0, generate everything and
2127 store into 'result'. Successive reads will be served off
2131 traceframe_read_info (cs
.current_traceframe
, &result
);
2134 if (offset
>= result
.length ())
2136 /* We're out of data. */
2141 if (len
> result
.length () - offset
)
2142 len
= result
.length () - offset
;
2144 memcpy (readbuf
, result
.c_str () + offset
, len
);
2148 /* Handle qXfer:fdpic:read. */
2151 handle_qxfer_fdpic (const char *annex
, gdb_byte
*readbuf
,
2152 const gdb_byte
*writebuf
, ULONGEST offset
, LONGEST len
)
2154 if (!the_target
->supports_read_loadmap ())
2157 if (current_thread
== NULL
)
2160 return the_target
->read_loadmap (annex
, offset
, readbuf
, len
);
2163 /* Handle qXfer:btrace:read. */
2166 handle_qxfer_btrace (const char *annex
,
2167 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2168 ULONGEST offset
, LONGEST len
)
2170 client_state
&cs
= get_client_state ();
2171 static std::string cache
;
2172 struct thread_info
*thread
;
2173 enum btrace_read_type type
;
2176 if (writebuf
!= NULL
)
2179 if (cs
.general_thread
== null_ptid
2180 || cs
.general_thread
== minus_one_ptid
)
2182 strcpy (cs
.own_buf
, "E.Must select a single thread.");
2186 thread
= find_thread_ptid (cs
.general_thread
);
2189 strcpy (cs
.own_buf
, "E.No such thread.");
2193 if (thread
->btrace
== NULL
)
2195 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
2199 if (strcmp (annex
, "all") == 0)
2200 type
= BTRACE_READ_ALL
;
2201 else if (strcmp (annex
, "new") == 0)
2202 type
= BTRACE_READ_NEW
;
2203 else if (strcmp (annex
, "delta") == 0)
2204 type
= BTRACE_READ_DELTA
;
2207 strcpy (cs
.own_buf
, "E.Bad annex.");
2217 result
= target_read_btrace (thread
->btrace
, &cache
, type
);
2219 memcpy (cs
.own_buf
, cache
.c_str (), cache
.length ());
2221 catch (const gdb_exception_error
&exception
)
2223 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
2230 else if (offset
> cache
.length ())
2236 if (len
> cache
.length () - offset
)
2237 len
= cache
.length () - offset
;
2239 memcpy (readbuf
, cache
.c_str () + offset
, len
);
2244 /* Handle qXfer:btrace-conf:read. */
2247 handle_qxfer_btrace_conf (const char *annex
,
2248 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
2249 ULONGEST offset
, LONGEST len
)
2251 client_state
&cs
= get_client_state ();
2252 static std::string cache
;
2253 struct thread_info
*thread
;
2256 if (writebuf
!= NULL
)
2259 if (annex
[0] != '\0')
2262 if (cs
.general_thread
== null_ptid
2263 || cs
.general_thread
== minus_one_ptid
)
2265 strcpy (cs
.own_buf
, "E.Must select a single thread.");
2269 thread
= find_thread_ptid (cs
.general_thread
);
2272 strcpy (cs
.own_buf
, "E.No such thread.");
2276 if (thread
->btrace
== NULL
)
2278 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
2288 result
= target_read_btrace_conf (thread
->btrace
, &cache
);
2290 memcpy (cs
.own_buf
, cache
.c_str (), cache
.length ());
2292 catch (const gdb_exception_error
&exception
)
2294 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
2301 else if (offset
> cache
.length ())
2307 if (len
> cache
.length () - offset
)
2308 len
= cache
.length () - offset
;
2310 memcpy (readbuf
, cache
.c_str () + offset
, len
);
2315 static const struct qxfer qxfer_packets
[] =
2317 { "auxv", handle_qxfer_auxv
},
2318 { "btrace", handle_qxfer_btrace
},
2319 { "btrace-conf", handle_qxfer_btrace_conf
},
2320 { "exec-file", handle_qxfer_exec_file
},
2321 { "fdpic", handle_qxfer_fdpic
},
2322 { "features", handle_qxfer_features
},
2323 { "libraries", handle_qxfer_libraries
},
2324 { "libraries-svr4", handle_qxfer_libraries_svr4
},
2325 { "osdata", handle_qxfer_osdata
},
2326 { "siginfo", handle_qxfer_siginfo
},
2327 { "statictrace", handle_qxfer_statictrace
},
2328 { "threads", handle_qxfer_threads
},
2329 { "traceframe-info", handle_qxfer_traceframe_info
},
2333 handle_qxfer (char *own_buf
, int packet_len
, int *new_packet_len_p
)
2341 if (!startswith (own_buf
, "qXfer:"))
2344 /* Grab the object, r/w and annex. */
2345 if (decode_xfer (own_buf
+ 6, &object
, &rw
, &annex
, &offset
) < 0)
2347 write_enn (own_buf
);
2352 i
< sizeof (qxfer_packets
) / sizeof (qxfer_packets
[0]);
2355 const struct qxfer
*q
= &qxfer_packets
[i
];
2357 if (strcmp (object
, q
->object
) == 0)
2359 if (strcmp (rw
, "read") == 0)
2361 unsigned char *data
;
2366 /* Grab the offset and length. */
2367 if (decode_xfer_read (offset
, &ofs
, &len
) < 0)
2369 write_enn (own_buf
);
2373 /* Read one extra byte, as an indicator of whether there is
2375 if (len
> PBUFSIZ
- 2)
2377 data
= (unsigned char *) malloc (len
+ 1);
2380 write_enn (own_buf
);
2383 n
= (*q
->xfer
) (annex
, data
, NULL
, ofs
, len
+ 1);
2391 /* Preserve error message. */
2394 write_enn (own_buf
);
2396 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, len
, 1);
2398 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, n
, 0);
2403 else if (strcmp (rw
, "write") == 0)
2408 unsigned char *data
;
2410 strcpy (own_buf
, "E00");
2411 data
= (unsigned char *) malloc (packet_len
- (offset
- own_buf
));
2414 write_enn (own_buf
);
2417 if (decode_xfer_write (offset
, packet_len
- (offset
- own_buf
),
2418 &ofs
, &len
, data
) < 0)
2421 write_enn (own_buf
);
2425 n
= (*q
->xfer
) (annex
, NULL
, data
, ofs
, len
);
2433 /* Preserve error message. */
2436 write_enn (own_buf
);
2438 sprintf (own_buf
, "%x", n
);
2451 /* Compute 32 bit CRC from inferior memory.
2453 On success, return 32 bit CRC.
2454 On failure, return (unsigned long long) -1. */
2456 static unsigned long long
2457 crc32 (CORE_ADDR base
, int len
, unsigned int crc
)
2461 unsigned char byte
= 0;
2463 /* Return failure if memory read fails. */
2464 if (read_inferior_memory (base
, &byte
, 1) != 0)
2465 return (unsigned long long) -1;
2467 crc
= xcrc32 (&byte
, 1, crc
);
2470 return (unsigned long long) crc
;
2473 /* Parse the qMemTags packet request into ADDR and LEN. */
2476 parse_fetch_memtags_request (char *request
, CORE_ADDR
*addr
, size_t *len
,
2479 gdb_assert (startswith (request
, "qMemTags:"));
2481 const char *p
= request
+ strlen ("qMemTags:");
2483 /* Read address and length. */
2484 unsigned int length
= 0;
2485 p
= decode_m_packet_params (p
, addr
, &length
, ':');
2488 /* Read the tag type. */
2489 ULONGEST tag_type
= 0;
2490 p
= unpack_varlen_hex (p
, &tag_type
);
2491 *type
= (int) tag_type
;
2494 /* Add supported btrace packets to BUF. */
2497 supported_btrace_packets (char *buf
)
2499 strcat (buf
, ";Qbtrace:bts+");
2500 strcat (buf
, ";Qbtrace-conf:bts:size+");
2501 strcat (buf
, ";Qbtrace:pt+");
2502 strcat (buf
, ";Qbtrace-conf:pt:size+");
2503 strcat (buf
, ";Qbtrace-conf:pt:ptwrite+");
2504 strcat (buf
, ";Qbtrace-conf:pt:event-tracing+");
2505 strcat (buf
, ";Qbtrace:off+");
2506 strcat (buf
, ";qXfer:btrace:read+");
2507 strcat (buf
, ";qXfer:btrace-conf:read+");
2510 /* Handle all of the extended 'q' packets. */
2513 handle_query (char *own_buf
, int packet_len
, int *new_packet_len_p
)
2515 client_state
&cs
= get_client_state ();
2516 static owning_intrusive_list
<process_info
>::iterator process_iter
;
2517 static owning_intrusive_list
<thread_info
>::iterator thread_iter
;
2519 auto init_thread_iter
= [&] ()
2521 process_iter
= all_processes
.begin ();
2522 owning_intrusive_list
<thread_info
> *thread_list
;
2524 for (; process_iter
!= all_processes
.end (); ++process_iter
)
2526 thread_list
= &process_iter
->thread_list ();
2527 thread_iter
= thread_list
->begin ();
2528 if (thread_iter
!= thread_list
->end ())
2531 /* Make sure that there is at least one thread to iterate. */
2532 gdb_assert (process_iter
!= all_processes
.end ());
2533 gdb_assert (thread_iter
!= thread_list
->end ());
2536 auto advance_thread_iter
= [&] ()
2538 /* The loop below is written in the natural way as-if we'd always
2539 start at the beginning of the inferior list. This fast forwards
2540 the algorithm to the actual current position. */
2541 owning_intrusive_list
<thread_info
> *thread_list
2542 = &process_iter
->thread_list ();
2545 for (; process_iter
!= all_processes
.end (); ++process_iter
)
2547 thread_list
= &process_iter
->thread_list ();
2548 thread_iter
= thread_list
->begin ();
2549 while (thread_iter
!= thread_list
->end ())
2558 /* Reply the current thread id. */
2559 if (strcmp ("qC", own_buf
) == 0 && !disable_packet_qC
)
2562 require_running_or_return (own_buf
);
2564 if (cs
.general_thread
!= null_ptid
&& cs
.general_thread
!= minus_one_ptid
)
2565 ptid
= cs
.general_thread
;
2568 init_thread_iter ();
2569 ptid
= thread_iter
->id
;
2572 sprintf (own_buf
, "QC");
2574 write_ptid (own_buf
, ptid
);
2578 if (strcmp ("qSymbol::", own_buf
) == 0)
2580 scoped_restore_current_thread restore_thread
;
2582 /* For qSymbol, GDB only changes the current thread if the
2583 previous current thread was of a different process. So if
2584 the previous thread is gone, we need to pick another one of
2585 the same process. This can happen e.g., if we followed an
2586 exec in a non-leader thread. */
2587 if (current_thread
== NULL
)
2589 thread_info
*any_thread
2590 = find_any_thread_of_pid (cs
.general_thread
.pid ());
2591 switch_to_thread (any_thread
);
2593 /* Just in case, if we didn't find a thread, then bail out
2594 instead of crashing. */
2595 if (current_thread
== NULL
)
2597 write_enn (own_buf
);
2602 /* GDB is suggesting new symbols have been loaded. This may
2603 mean a new shared library has been detected as loaded, so
2604 take the opportunity to check if breakpoints we think are
2605 inserted, still are. Note that it isn't guaranteed that
2606 we'll see this when a shared library is loaded, and nor will
2607 we see this for unloads (although breakpoints in unloaded
2608 libraries shouldn't trigger), as GDB may not find symbols for
2609 the library at all. We also re-validate breakpoints when we
2610 see a second GDB breakpoint for the same address, and or when
2611 we access breakpoint shadows. */
2612 validate_breakpoints ();
2614 if (target_supports_tracepoints ())
2615 tracepoint_look_up_symbols ();
2617 if (current_thread
!= NULL
)
2618 the_target
->look_up_symbols ();
2620 strcpy (own_buf
, "OK");
2624 if (!disable_packet_qfThreadInfo
)
2626 if (strcmp ("qfThreadInfo", own_buf
) == 0)
2628 require_running_or_return (own_buf
);
2629 init_thread_iter ();
2632 ptid_t ptid
= thread_iter
->id
;
2633 write_ptid (own_buf
, ptid
);
2634 advance_thread_iter ();
2638 if (strcmp ("qsThreadInfo", own_buf
) == 0)
2640 require_running_or_return (own_buf
);
2641 /* We're done if the process iterator hits the end of the
2643 if (process_iter
!= all_processes
.end ())
2646 ptid_t ptid
= thread_iter
->id
;
2647 write_ptid (own_buf
, ptid
);
2648 advance_thread_iter ();
2653 sprintf (own_buf
, "l");
2659 if (the_target
->supports_read_offsets ()
2660 && strcmp ("qOffsets", own_buf
) == 0)
2662 CORE_ADDR text
, data
;
2664 require_running_or_return (own_buf
);
2665 if (the_target
->read_offsets (&text
, &data
))
2666 sprintf (own_buf
, "Text=%lX;Data=%lX;Bss=%lX",
2667 (long)text
, (long)data
, (long)data
);
2669 write_enn (own_buf
);
2674 /* Protocol features query. */
2675 if (startswith (own_buf
, "qSupported")
2676 && (own_buf
[10] == ':' || own_buf
[10] == '\0'))
2678 char *p
= &own_buf
[10];
2679 int gdb_supports_qRelocInsn
= 0;
2681 /* Process each feature being provided by GDB. The first
2682 feature will follow a ':', and latter features will follow
2686 std::vector
<std::string
> qsupported
;
2687 std::vector
<const char *> unknowns
;
2689 /* Two passes, to avoid nested strtok calls in
2690 target_process_qsupported. */
2692 for (p
= strtok_r (p
+ 1, ";", &saveptr
);
2694 p
= strtok_r (NULL
, ";", &saveptr
))
2695 qsupported
.emplace_back (p
);
2697 for (const std::string
&feature
: qsupported
)
2699 if (feature
== "multiprocess+")
2701 /* GDB supports and wants multi-process support if
2703 if (target_supports_multi_process ())
2704 cs
.multi_process
= 1;
2706 else if (feature
== "qRelocInsn+")
2708 /* GDB supports relocate instruction requests. */
2709 gdb_supports_qRelocInsn
= 1;
2711 else if (feature
== "swbreak+")
2713 /* GDB wants us to report whether a trap is caused
2714 by a software breakpoint and for us to handle PC
2715 adjustment if necessary on this target. */
2716 if (target_supports_stopped_by_sw_breakpoint ())
2717 cs
.swbreak_feature
= 1;
2719 else if (feature
== "hwbreak+")
2721 /* GDB wants us to report whether a trap is caused
2722 by a hardware breakpoint. */
2723 if (target_supports_stopped_by_hw_breakpoint ())
2724 cs
.hwbreak_feature
= 1;
2726 else if (feature
== "fork-events+")
2728 /* GDB supports and wants fork events if possible. */
2729 if (target_supports_fork_events ())
2730 cs
.report_fork_events
= 1;
2732 else if (feature
== "vfork-events+")
2734 /* GDB supports and wants vfork events if possible. */
2735 if (target_supports_vfork_events ())
2736 cs
.report_vfork_events
= 1;
2738 else if (feature
== "exec-events+")
2740 /* GDB supports and wants exec events if possible. */
2741 if (target_supports_exec_events ())
2742 cs
.report_exec_events
= 1;
2744 else if (feature
== "vContSupported+")
2745 cs
.vCont_supported
= 1;
2746 else if (feature
== "QThreadEvents+")
2748 else if (feature
== "QThreadOptions+")
2750 else if (feature
== "no-resumed+")
2752 /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
2754 report_no_resumed
= true;
2756 else if (feature
== "memory-tagging+")
2758 /* GDB supports memory tagging features. */
2759 if (target_supports_memory_tagging ())
2760 cs
.memory_tagging_feature
= true;
2762 else if (feature
== "error-message+")
2763 cs
.error_message_supported
= true;
2766 /* Move the unknown features all together. */
2767 unknowns
.push_back (feature
.c_str ());
2771 /* Give the target backend a chance to process the unknown
2773 target_process_qsupported (unknowns
);
2777 "PacketSize=%x;QPassSignals+;QProgramSignals+;"
2778 "QStartupWithShell+;QEnvironmentHexEncoded+;"
2779 "QEnvironmentReset+;QEnvironmentUnset+;"
2783 if (target_supports_catch_syscall ())
2784 strcat (own_buf
, ";QCatchSyscalls+");
2786 if (the_target
->supports_qxfer_libraries_svr4 ())
2787 strcat (own_buf
, ";qXfer:libraries-svr4:read+"
2788 ";augmented-libraries-svr4-read+");
2791 /* We do not have any hook to indicate whether the non-SVR4 target
2792 backend supports qXfer:libraries:read, so always report it. */
2793 strcat (own_buf
, ";qXfer:libraries:read+");
2796 if (the_target
->supports_read_auxv ())
2797 strcat (own_buf
, ";qXfer:auxv:read+");
2799 if (the_target
->supports_qxfer_siginfo ())
2800 strcat (own_buf
, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2802 if (the_target
->supports_read_loadmap ())
2803 strcat (own_buf
, ";qXfer:fdpic:read+");
2805 /* We always report qXfer:features:read, as targets may
2806 install XML files on a subsequent call to arch_setup.
2807 If we reported to GDB on startup that we don't support
2808 qXfer:feature:read at all, we will never be re-queried. */
2809 strcat (own_buf
, ";qXfer:features:read+");
2811 if (cs
.transport_is_reliable
)
2812 strcat (own_buf
, ";QStartNoAckMode+");
2814 if (the_target
->supports_qxfer_osdata ())
2815 strcat (own_buf
, ";qXfer:osdata:read+");
2817 if (target_supports_multi_process ())
2818 strcat (own_buf
, ";multiprocess+");
2820 if (target_supports_fork_events ())
2821 strcat (own_buf
, ";fork-events+");
2823 if (target_supports_vfork_events ())
2824 strcat (own_buf
, ";vfork-events+");
2826 if (target_supports_exec_events ())
2827 strcat (own_buf
, ";exec-events+");
2829 if (target_supports_non_stop ())
2830 strcat (own_buf
, ";QNonStop+");
2832 if (target_supports_disable_randomization ())
2833 strcat (own_buf
, ";QDisableRandomization+");
2835 strcat (own_buf
, ";qXfer:threads:read+");
2837 if (target_supports_tracepoints ())
2839 strcat (own_buf
, ";ConditionalTracepoints+");
2840 strcat (own_buf
, ";TraceStateVariables+");
2841 strcat (own_buf
, ";TracepointSource+");
2842 strcat (own_buf
, ";DisconnectedTracing+");
2843 if (gdb_supports_qRelocInsn
&& target_supports_fast_tracepoints ())
2844 strcat (own_buf
, ";FastTracepoints+");
2845 strcat (own_buf
, ";StaticTracepoints+");
2846 strcat (own_buf
, ";InstallInTrace+");
2847 strcat (own_buf
, ";qXfer:statictrace:read+");
2848 strcat (own_buf
, ";qXfer:traceframe-info:read+");
2849 strcat (own_buf
, ";EnableDisableTracepoints+");
2850 strcat (own_buf
, ";QTBuffer:size+");
2851 strcat (own_buf
, ";tracenz+");
2854 if (target_supports_hardware_single_step ()
2855 || target_supports_software_single_step () )
2857 strcat (own_buf
, ";ConditionalBreakpoints+");
2859 strcat (own_buf
, ";BreakpointCommands+");
2861 if (target_supports_agent ())
2862 strcat (own_buf
, ";QAgent+");
2864 if (the_target
->supports_btrace ())
2865 supported_btrace_packets (own_buf
);
2867 if (target_supports_stopped_by_sw_breakpoint ())
2868 strcat (own_buf
, ";swbreak+");
2870 if (target_supports_stopped_by_hw_breakpoint ())
2871 strcat (own_buf
, ";hwbreak+");
2873 if (the_target
->supports_pid_to_exec_file ())
2874 strcat (own_buf
, ";qXfer:exec-file:read+");
2876 strcat (own_buf
, ";vContSupported+");
2878 gdb_thread_options supported_options
= target_supported_thread_options ();
2879 if (supported_options
!= 0)
2881 char *end_buf
= own_buf
+ strlen (own_buf
);
2882 sprintf (end_buf
, ";QThreadOptions=%s",
2883 phex_nz (supported_options
, sizeof (supported_options
)));
2886 strcat (own_buf
, ";QThreadEvents+");
2888 strcat (own_buf
, ";no-resumed+");
2890 if (target_supports_memory_tagging ())
2891 strcat (own_buf
, ";memory-tagging+");
2893 /* Reinitialize components as needed for the new connection. */
2894 hostio_handle_new_gdb_connection ();
2895 target_handle_new_gdb_connection ();
2900 /* Thread-local storage support. */
2901 if (the_target
->supports_get_tls_address ()
2902 && startswith (own_buf
, "qGetTLSAddr:"))
2904 char *p
= own_buf
+ 12;
2905 CORE_ADDR parts
[2], address
= 0;
2907 ptid_t ptid
= null_ptid
;
2909 require_running_or_return (own_buf
);
2911 for (i
= 0; i
< 3; i
++)
2919 p2
= strchr (p
, ',');
2932 ptid
= read_ptid (p
, NULL
);
2934 decode_address (&parts
[i
- 1], p
, len
);
2938 if (p
!= NULL
|| i
< 3)
2942 struct thread_info
*thread
= find_thread_ptid (ptid
);
2947 err
= the_target
->get_tls_address (thread
, parts
[0], parts
[1],
2953 strcpy (own_buf
, paddress(address
));
2958 write_enn (own_buf
);
2962 /* Otherwise, pretend we do not understand this packet. */
2965 /* Windows OS Thread Information Block address support. */
2966 if (the_target
->supports_get_tib_address ()
2967 && startswith (own_buf
, "qGetTIBAddr:"))
2972 ptid_t ptid
= read_ptid (own_buf
+ 12, &annex
);
2974 n
= the_target
->get_tib_address (ptid
, &tlb
);
2977 strcpy (own_buf
, paddress(tlb
));
2982 write_enn (own_buf
);
2988 /* Handle "monitor" commands. */
2989 if (startswith (own_buf
, "qRcmd,"))
2991 char *mon
= (char *) malloc (PBUFSIZ
);
2992 int len
= strlen (own_buf
+ 6);
2996 write_enn (own_buf
);
3001 || hex2bin (own_buf
+ 6, (gdb_byte
*) mon
, len
/ 2) != len
/ 2)
3003 write_enn (own_buf
);
3007 mon
[len
/ 2] = '\0';
3011 if (the_target
->handle_monitor_command (mon
) == 0)
3012 /* Default processing. */
3013 handle_monitor_command (mon
, own_buf
);
3019 if (startswith (own_buf
, "qSearch:memory:"))
3021 require_running_or_return (own_buf
);
3022 handle_search_memory (own_buf
, packet_len
);
3026 if (strcmp (own_buf
, "qAttached") == 0
3027 || startswith (own_buf
, "qAttached:"))
3029 struct process_info
*process
;
3031 if (own_buf
[sizeof ("qAttached") - 1])
3033 int pid
= strtoul (own_buf
+ sizeof ("qAttached:") - 1, NULL
, 16);
3034 process
= find_process_pid (pid
);
3038 require_running_or_return (own_buf
);
3039 process
= current_process ();
3042 if (process
== NULL
)
3044 write_enn (own_buf
);
3048 strcpy (own_buf
, process
->attached
? "1" : "0");
3052 if (startswith (own_buf
, "qCRC:"))
3054 /* CRC check (compare-section). */
3058 unsigned long long crc
;
3060 require_running_or_return (own_buf
);
3061 comma
= unpack_varlen_hex (own_buf
+ 5, &base
);
3062 if (*comma
++ != ',')
3064 write_enn (own_buf
);
3067 len
= strtoul (comma
, NULL
, 16);
3068 crc
= crc32 (base
, len
, 0xffffffff);
3069 /* Check for memory failure. */
3070 if (crc
== (unsigned long long) -1)
3072 write_enn (own_buf
);
3075 sprintf (own_buf
, "C%lx", (unsigned long) crc
);
3079 if (handle_qxfer (own_buf
, packet_len
, new_packet_len_p
))
3082 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf
))
3085 /* Handle fetch memory tags packets. */
3086 if (startswith (own_buf
, "qMemTags:")
3087 && target_supports_memory_tagging ())
3089 gdb::byte_vector tags
;
3094 require_running_or_return (own_buf
);
3096 parse_fetch_memtags_request (own_buf
, &addr
, &len
, &type
);
3098 bool ret
= the_target
->fetch_memtags (addr
, len
, tags
, type
);
3101 ret
= create_fetch_memtags_reply (own_buf
, tags
);
3104 write_enn (own_buf
);
3106 *new_packet_len_p
= strlen (own_buf
);
3110 /* Otherwise we didn't know what packet it was. Say we didn't
3115 static void gdb_wants_all_threads_stopped (void);
3116 static void resume (struct thread_resume
*actions
, size_t n
);
3118 /* The callback that is passed to visit_actioned_threads. */
3119 typedef int (visit_actioned_threads_callback_ftype
)
3120 (const struct thread_resume
*, struct thread_info
*);
3122 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
3123 true if CALLBACK returns true. Returns false if no matching thread
3124 is found or CALLBACK results false.
3125 Note: This function is itself a callback for find_thread. */
3128 visit_actioned_threads (thread_info
*thread
,
3129 const struct thread_resume
*actions
,
3131 visit_actioned_threads_callback_ftype
*callback
)
3133 for (size_t i
= 0; i
< num_actions
; i
++)
3135 const struct thread_resume
*action
= &actions
[i
];
3137 if (action
->thread
== minus_one_ptid
3138 || action
->thread
== thread
->id
3139 || ((action
->thread
.pid ()
3140 == thread
->id
.pid ())
3141 && action
->thread
.lwp () == -1))
3143 if ((*callback
) (action
, thread
))
3151 /* Callback for visit_actioned_threads. If the thread has a pending
3152 status to report, report it now. */
3155 handle_pending_status (const struct thread_resume
*resumption
,
3156 struct thread_info
*thread
)
3158 client_state
&cs
= get_client_state ();
3159 if (thread
->status_pending_p
)
3161 thread
->status_pending_p
= 0;
3163 cs
.last_status
= thread
->last_status
;
3164 cs
.last_ptid
= thread
->id
;
3165 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, cs
.last_status
);
3171 /* Parse vCont packets. */
3173 handle_v_cont (char *own_buf
)
3177 struct thread_resume
*resume_info
;
3178 struct thread_resume default_action
{ null_ptid
};
3180 /* Count the number of semicolons in the packet. There should be one
3181 for every action. */
3187 p
= strchr (p
, ';');
3190 resume_info
= (struct thread_resume
*) malloc (n
* sizeof (resume_info
[0]));
3191 if (resume_info
== NULL
)
3199 memset (&resume_info
[i
], 0, sizeof resume_info
[i
]);
3201 if (p
[0] == 's' || p
[0] == 'S')
3202 resume_info
[i
].kind
= resume_step
;
3203 else if (p
[0] == 'r')
3204 resume_info
[i
].kind
= resume_step
;
3205 else if (p
[0] == 'c' || p
[0] == 'C')
3206 resume_info
[i
].kind
= resume_continue
;
3207 else if (p
[0] == 't')
3208 resume_info
[i
].kind
= resume_stop
;
3212 if (p
[0] == 'S' || p
[0] == 'C')
3215 int sig
= strtol (p
+ 1, &q
, 16);
3220 if (!gdb_signal_to_host_p ((enum gdb_signal
) sig
))
3222 resume_info
[i
].sig
= gdb_signal_to_host ((enum gdb_signal
) sig
);
3224 else if (p
[0] == 'r')
3228 p
= unpack_varlen_hex (p
+ 1, &addr
);
3229 resume_info
[i
].step_range_start
= addr
;
3234 p
= unpack_varlen_hex (p
+ 1, &addr
);
3235 resume_info
[i
].step_range_end
= addr
;
3244 resume_info
[i
].thread
= minus_one_ptid
;
3245 default_action
= resume_info
[i
];
3247 /* Note: we don't increment i here, we'll overwrite this entry
3248 the next time through. */
3250 else if (p
[0] == ':')
3253 ptid_t ptid
= read_ptid (p
+ 1, &q
);
3258 if (p
[0] != ';' && p
[0] != 0)
3261 resume_info
[i
].thread
= ptid
;
3268 resume_info
[i
] = default_action
;
3270 resume (resume_info
, n
);
3275 write_enn (own_buf
);
3280 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
3283 resume (struct thread_resume
*actions
, size_t num_actions
)
3285 client_state
&cs
= get_client_state ();
3288 /* Check if among the threads that GDB wants actioned, there's
3289 one with a pending status to report. If so, skip actually
3290 resuming/stopping and report the pending event
3293 thread_info
*thread_with_status
= find_thread ([&] (thread_info
*thread
)
3295 return visit_actioned_threads (thread
, actions
, num_actions
,
3296 handle_pending_status
);
3299 if (thread_with_status
!= NULL
)
3305 the_target
->resume (actions
, num_actions
);
3308 write_ok (cs
.own_buf
);
3311 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
, 0, 1);
3313 if (cs
.last_status
.kind () == TARGET_WAITKIND_NO_RESUMED
3314 && !report_no_resumed
)
3316 /* The client does not support this stop reply. At least
3318 sprintf (cs
.own_buf
, "E.No unwaited-for children left.");
3319 disable_async_io ();
3323 if (cs
.last_status
.kind () != TARGET_WAITKIND_EXITED
3324 && cs
.last_status
.kind () != TARGET_WAITKIND_SIGNALLED
3325 && cs
.last_status
.kind () != TARGET_WAITKIND_THREAD_EXITED
3326 && cs
.last_status
.kind () != TARGET_WAITKIND_NO_RESUMED
)
3327 current_thread
->last_status
= cs
.last_status
;
3329 /* From the client's perspective, all-stop mode always stops all
3330 threads implicitly (and the target backend has already done
3331 so by now). Tag all threads as "want-stopped", so we don't
3332 resume them implicitly without the client telling us to. */
3333 gdb_wants_all_threads_stopped ();
3334 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, cs
.last_status
);
3335 disable_async_io ();
3337 if (cs
.last_status
.kind () == TARGET_WAITKIND_EXITED
3338 || cs
.last_status
.kind () == TARGET_WAITKIND_SIGNALLED
)
3339 target_mourn_inferior (cs
.last_ptid
);
3343 /* Attach to a new program. */
3345 handle_v_attach (char *own_buf
)
3347 client_state
&cs
= get_client_state ();
3349 int pid
= strtol (own_buf
+ 8, NULL
, 16);
3353 if (attach_inferior (pid
) == 0)
3355 /* Don't report shared library events after attaching, even if
3356 some libraries are preloaded. GDB will always poll the
3357 library list. Avoids the "stopped by shared library event"
3358 notice on the GDB side. */
3359 current_process ()->dlls_changed
= false;
3363 /* In non-stop, we don't send a resume reply. Stop events
3364 will follow up using the normal notification
3369 prepare_resume_reply (own_buf
, cs
.last_ptid
, cs
.last_status
);
3373 /* Not supported. */
3377 catch (const gdb_exception_error
&exception
)
3379 sprintf (own_buf
, "E.%s", exception
.what ());
3383 /* Decode an argument from the vRun packet buffer. PTR points to the
3384 first hex-encoded character in the buffer, and LEN is the number of
3385 characters to read from the packet buffer.
3387 If the argument decoding is successful, return a buffer containing the
3388 decoded argument, including a null terminator at the end.
3390 If the argument decoding fails for any reason, return nullptr. */
3392 static gdb::unique_xmalloc_ptr
<char>
3393 decode_v_run_arg (const char *ptr
, size_t len
)
3395 /* Two hex characters are required for each decoded byte. */
3399 /* The length in bytes needed for the decoded argument. */
3402 /* Buffer to decode the argument into. The '+ 1' is for the null
3403 terminator we will add. */
3404 char *arg
= (char *) xmalloc (len
+ 1);
3406 /* Decode the argument from the packet and add a null terminator. We do
3407 this within a try block as invalid characters within the PTR buffer
3408 will cause hex2bin to throw an exception. Our caller relies on us
3409 returning nullptr in order to clean up some memory allocations. */
3412 hex2bin (ptr
, (gdb_byte
*) arg
, len
);
3415 catch (const gdb_exception_error
&exception
)
3420 return gdb::unique_xmalloc_ptr
<char> (arg
);
3423 /* Run a new program. */
3425 handle_v_run (char *own_buf
)
3427 client_state
&cs
= get_client_state ();
3429 std::vector
<char *> new_argv
;
3430 gdb::unique_xmalloc_ptr
<char> new_program_name
;
3433 for (i
= 0, p
= own_buf
+ strlen ("vRun;");
3434 /* Exit condition is at the end of the loop. */;
3435 p
= next_p
+ 1, ++i
)
3437 next_p
= strchr (p
, ';');
3439 next_p
= p
+ strlen (p
);
3441 if (i
== 0 && p
== next_p
)
3443 /* No program specified. */
3444 gdb_assert (new_program_name
== nullptr);
3446 else if (p
== next_p
)
3448 /* Empty argument. */
3449 new_argv
.push_back (xstrdup (""));
3453 /* The length of the argument string in the packet. */
3454 size_t len
= next_p
- p
;
3456 gdb::unique_xmalloc_ptr
<char> arg
= decode_v_run_arg (p
, len
);
3459 write_enn (own_buf
);
3460 free_vector_argv (new_argv
);
3465 new_program_name
= std::move (arg
);
3467 new_argv
.push_back (arg
.release ());
3469 if (*next_p
== '\0')
3473 if (new_program_name
== nullptr)
3475 /* GDB didn't specify a program to run. Use the program from the
3476 last run with the new argument list. */
3477 if (program_path
.get () == nullptr)
3479 write_enn (own_buf
);
3480 free_vector_argv (new_argv
);
3485 program_path
.set (new_program_name
.get ());
3487 /* Free the old argv and install the new one. */
3488 free_vector_argv (program_args
);
3489 program_args
= new_argv
;
3493 target_create_inferior (program_path
.get (), program_args
);
3495 catch (const gdb_exception_error
&exception
)
3497 sprintf (own_buf
, "E.%s", exception
.what ());
3501 if (cs
.last_status
.kind () == TARGET_WAITKIND_STOPPED
)
3503 prepare_resume_reply (own_buf
, cs
.last_ptid
, cs
.last_status
);
3505 /* In non-stop, sending a resume reply doesn't set the general
3506 thread, but GDB assumes a vRun sets it (this is so GDB can
3507 query which is the main thread of the new inferior. */
3509 cs
.general_thread
= cs
.last_ptid
;
3512 write_enn (own_buf
);
3517 handle_v_kill (char *own_buf
)
3519 client_state
&cs
= get_client_state ();
3521 char *p
= &own_buf
[6];
3522 if (cs
.multi_process
)
3523 pid
= strtol (p
, NULL
, 16);
3527 process_info
*proc
= find_process_pid (pid
);
3529 if (proc
!= nullptr && kill_inferior (proc
) == 0)
3531 cs
.last_status
.set_signalled (GDB_SIGNAL_KILL
);
3532 cs
.last_ptid
= ptid_t (pid
);
3533 discard_queued_stop_replies (cs
.last_ptid
);
3537 write_enn (own_buf
);
3540 /* Handle all of the extended 'v' packets. */
3542 handle_v_requests (char *own_buf
, int packet_len
, int *new_packet_len
)
3544 client_state
&cs
= get_client_state ();
3545 if (!disable_packet_vCont
)
3547 if (strcmp (own_buf
, "vCtrlC") == 0)
3549 the_target
->request_interrupt ();
3554 if (startswith (own_buf
, "vCont;"))
3556 handle_v_cont (own_buf
);
3560 if (startswith (own_buf
, "vCont?"))
3562 strcpy (own_buf
, "vCont;c;C;t");
3564 if (target_supports_hardware_single_step ()
3565 || target_supports_software_single_step ()
3566 || !cs
.vCont_supported
)
3568 /* If target supports single step either by hardware or by
3569 software, add actions s and S to the list of supported
3570 actions. On the other hand, if GDB doesn't request the
3571 supported vCont actions in qSupported packet, add s and
3572 S to the list too. */
3573 own_buf
= own_buf
+ strlen (own_buf
);
3574 strcpy (own_buf
, ";s;S");
3577 if (target_supports_range_stepping ())
3579 own_buf
= own_buf
+ strlen (own_buf
);
3580 strcpy (own_buf
, ";r");
3586 if (startswith (own_buf
, "vFile:")
3587 && handle_vFile (own_buf
, packet_len
, new_packet_len
))
3590 if (startswith (own_buf
, "vAttach;"))
3592 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3594 fprintf (stderr
, "Already debugging a process\n");
3595 write_enn (own_buf
);
3598 handle_v_attach (own_buf
);
3602 if (startswith (own_buf
, "vRun;"))
3604 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3606 fprintf (stderr
, "Already debugging a process\n");
3607 write_enn (own_buf
);
3610 handle_v_run (own_buf
);
3614 if (startswith (own_buf
, "vKill;"))
3616 if (!target_running ())
3618 fprintf (stderr
, "No process to kill\n");
3619 write_enn (own_buf
);
3622 handle_v_kill (own_buf
);
3626 if (handle_notif_ack (own_buf
, packet_len
))
3629 /* Otherwise we didn't know what packet it was. Say we didn't
3635 /* Resume thread and wait for another event. In non-stop mode,
3636 don't really wait here, but return immediately to the event
3639 myresume (char *own_buf
, int step
, int sig
)
3641 client_state
&cs
= get_client_state ();
3642 struct thread_resume resume_info
[2];
3644 int valid_cont_thread
;
3646 valid_cont_thread
= (cs
.cont_thread
!= null_ptid
3647 && cs
.cont_thread
!= minus_one_ptid
);
3649 if (step
|| sig
|| valid_cont_thread
)
3651 resume_info
[0].thread
= current_thread
->id
;
3653 resume_info
[0].kind
= resume_step
;
3655 resume_info
[0].kind
= resume_continue
;
3656 resume_info
[0].sig
= sig
;
3660 if (!valid_cont_thread
)
3662 resume_info
[n
].thread
= minus_one_ptid
;
3663 resume_info
[n
].kind
= resume_continue
;
3664 resume_info
[n
].sig
= 0;
3668 resume (resume_info
, n
);
3671 /* Callback for for_each_thread. Make a new stop reply for each
3675 queue_stop_reply_callback (thread_info
*thread
)
3677 /* For now, assume targets that don't have this callback also don't
3678 manage the thread's last_status field. */
3679 if (!the_target
->supports_thread_stopped ())
3681 struct vstop_notif
*new_notif
= new struct vstop_notif
;
3683 new_notif
->ptid
= thread
->id
;
3684 new_notif
->status
= thread
->last_status
;
3685 /* Pass the last stop reply back to GDB, but don't notify
3687 notif_event_enque (¬if_stop
, new_notif
);
3691 if (target_thread_stopped (thread
))
3693 threads_debug_printf
3694 ("Reporting thread %s as already stopped with %s",
3695 target_pid_to_str (thread
->id
).c_str (),
3696 thread
->last_status
.to_string ().c_str ());
3698 gdb_assert (thread
->last_status
.kind () != TARGET_WAITKIND_IGNORE
);
3700 /* Pass the last stop reply back to GDB, but don't notify
3702 queue_stop_reply (thread
->id
, thread
->last_status
);
3707 /* Set this inferior threads's state as "want-stopped". We won't
3708 resume this thread until the client gives us another action for
3712 gdb_wants_thread_stopped (thread_info
*thread
)
3714 thread
->last_resume_kind
= resume_stop
;
3716 if (thread
->last_status
.kind () == TARGET_WAITKIND_IGNORE
)
3718 /* Most threads are stopped implicitly (all-stop); tag that with
3720 thread
->last_status
.set_stopped (GDB_SIGNAL_0
);
3724 /* Set all threads' states as "want-stopped". */
3727 gdb_wants_all_threads_stopped (void)
3729 for_each_thread (gdb_wants_thread_stopped
);
3732 /* Callback for for_each_thread. If the thread is stopped with an
3733 interesting event, mark it as having a pending event. */
3736 set_pending_status_callback (thread_info
*thread
)
3738 if (thread
->last_status
.kind () != TARGET_WAITKIND_STOPPED
3739 || (thread
->last_status
.sig () != GDB_SIGNAL_0
3740 /* A breakpoint, watchpoint or finished step from a previous
3741 GDB run isn't considered interesting for a new GDB run.
3742 If we left those pending, the new GDB could consider them
3743 random SIGTRAPs. This leaves out real async traps. We'd
3744 have to peek into the (target-specific) siginfo to
3745 distinguish those. */
3746 && thread
->last_status
.sig () != GDB_SIGNAL_TRAP
))
3747 thread
->status_pending_p
= 1;
3750 /* Status handler for the '?' packet. */
3753 handle_status (char *own_buf
)
3755 client_state
&cs
= get_client_state ();
3757 /* GDB is connected, don't forward events to the target anymore. */
3758 for_each_process ([] (process_info
*process
) {
3759 process
->gdb_detached
= 0;
3762 /* In non-stop mode, we must send a stop reply for each stopped
3763 thread. In all-stop mode, just send one for the first stopped
3768 for_each_thread (queue_stop_reply_callback
);
3770 /* The first is sent immediately. OK is sent if there is no
3771 stopped thread, which is the same handling of the vStopped
3772 packet (by design). */
3773 notif_write_event (¬if_stop
, cs
.own_buf
);
3777 thread_info
*thread
= NULL
;
3779 target_pause_all (false);
3780 target_stabilize_threads ();
3781 gdb_wants_all_threads_stopped ();
3783 /* We can only report one status, but we might be coming out of
3784 non-stop -- if more than one thread is stopped with
3785 interesting events, leave events for the threads we're not
3786 reporting now pending. They'll be reported the next time the
3787 threads are resumed. Start by marking all interesting events
3789 for_each_thread (set_pending_status_callback
);
3791 /* Prefer the last thread that reported an event to GDB (even if
3792 that was a GDB_SIGNAL_TRAP). */
3793 if (cs
.last_status
.kind () != TARGET_WAITKIND_IGNORE
3794 && cs
.last_status
.kind () != TARGET_WAITKIND_EXITED
3795 && cs
.last_status
.kind () != TARGET_WAITKIND_SIGNALLED
)
3796 thread
= find_thread_ptid (cs
.last_ptid
);
3798 /* If the last event thread is not found for some reason, look
3799 for some other thread that might have an event to report. */
3801 thread
= find_thread ([] (thread_info
*thr_arg
)
3803 return thr_arg
->status_pending_p
;
3806 /* If we're still out of luck, simply pick the first thread in
3809 thread
= get_first_thread ();
3813 struct thread_info
*tp
= (struct thread_info
*) thread
;
3815 /* We're reporting this event, so it's no longer
3817 tp
->status_pending_p
= 0;
3819 /* GDB assumes the current thread is the thread we're
3820 reporting the status for. */
3821 cs
.general_thread
= thread
->id
;
3822 set_desired_thread ();
3824 gdb_assert (tp
->last_status
.kind () != TARGET_WAITKIND_IGNORE
);
3825 prepare_resume_reply (own_buf
, tp
->id
, tp
->last_status
);
3828 strcpy (own_buf
, "W00");
3833 gdbserver_version (void)
3835 printf ("GNU gdbserver %s%s\n"
3836 "Copyright (C) 2024 Free Software Foundation, Inc.\n"
3837 "gdbserver is free software, covered by the "
3838 "GNU General Public License.\n"
3839 "This gdbserver was configured as \"%s\"\n",
3840 PKGVERSION
, version
, host_name
);
3844 gdbserver_usage (FILE *stream
)
3846 fprintf (stream
, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3847 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3848 "\tgdbserver [OPTIONS] --multi COMM\n"
3850 "COMM may either be a tty device (for serial debugging),\n"
3851 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3852 "stdin/stdout of gdbserver.\n"
3853 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3854 "PID is the process ID to attach to, when --attach is specified.\n"
3856 "Operating modes:\n"
3858 " --attach Attach to running process PID.\n"
3859 " --multi Start server without a specific program, and\n"
3860 " only quit when explicitly commanded.\n"
3861 " --once Exit after the first connection has closed.\n"
3862 " --help Print this message and then exit.\n"
3863 " --version Display version information and exit.\n"
3867 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3868 " --disable-randomization\n"
3869 " Run PROG with address space randomization disabled.\n"
3870 " --no-disable-randomization\n"
3871 " Don't disable address space randomization when\n"
3873 " --startup-with-shell\n"
3874 " Start PROG using a shell. I.e., execs a shell that\n"
3875 " then execs PROG. (default)\n"
3876 " --no-startup-with-shell\n"
3877 " Exec PROG directly instead of using a shell.\n"
3878 " Disables argument globbing and variable substitution\n"
3879 " on UNIX-like systems.\n"
3883 " --debug[=OPT1,OPT2,...]\n"
3884 " Enable debugging output.\n"
3886 " all, threads, event-loop, remote\n"
3887 " With no options, 'threads' is assumed.\n"
3888 " Prefix an option with '-' to disable\n"
3889 " debugging of that component.\n"
3890 " --debug-format=OPT1[,OPT2,...]\n"
3891 " Specify extra content in debugging output.\n"
3896 " --disable-packet=OPT1[,OPT2,...]\n"
3897 " Disable support for RSP packets or features.\n"
3899 " vCont, T, Tthread, qC, qfThreadInfo and \n"
3900 " threads (disable all threading packets).\n"
3902 "For more information, consult the GDB manual (available as on-line \n"
3903 "info or a printed manual).\n");
3904 if (REPORT_BUGS_TO
[0] && stream
== stdout
)
3905 fprintf (stream
, "Report bugs to \"%s\".\n", REPORT_BUGS_TO
);
3909 gdbserver_show_disableable (FILE *stream
)
3911 fprintf (stream
, "Disableable packets:\n"
3912 " vCont \tAll vCont packets\n"
3913 " qC \tQuerying the current thread\n"
3914 " qfThreadInfo\tThread listing\n"
3915 " Tthread \tPassing the thread specifier in the "
3916 "T stop reply packet\n"
3917 " threads \tAll of the above\n"
3918 " T \tAll 'T' packets\n");
3921 /* Start up the event loop. This is the entry point to the event
3927 /* Loop until there is nothing to do. This is the entry point to
3928 the event loop engine. If nothing is ready at this time, wait
3929 for something to happen (via wait_for_event), then process it.
3930 Return when there are no longer event sources to wait for. */
3932 keep_processing_events
= true;
3933 while (keep_processing_events
)
3935 /* Any events already waiting in the queue? */
3936 int res
= gdb_do_one_event ();
3938 /* Was there an error? */
3943 /* We are done with the event loop. There are no more event sources
3944 to listen to. So we exit gdbserver. */
3948 kill_inferior_callback (process_info
*process
)
3950 kill_inferior (process
);
3951 discard_queued_stop_replies (ptid_t (process
->pid
));
3954 /* Call this when exiting gdbserver with possible inferiors that need
3955 to be killed or detached from. */
3958 detach_or_kill_for_exit (void)
3960 /* First print a list of the inferiors we will be killing/detaching.
3961 This is to assist the user, for example, in case the inferior unexpectedly
3962 dies after we exit: did we screw up or did the inferior exit on its own?
3963 Having this info will save some head-scratching. */
3965 if (have_started_inferiors_p ())
3967 fprintf (stderr
, "Killing process(es):");
3969 for_each_process ([] (process_info
*process
) {
3970 if (!process
->attached
)
3971 fprintf (stderr
, " %d", process
->pid
);
3974 fprintf (stderr
, "\n");
3976 if (have_attached_inferiors_p ())
3978 fprintf (stderr
, "Detaching process(es):");
3980 for_each_process ([] (process_info
*process
) {
3981 if (process
->attached
)
3982 fprintf (stderr
, " %d", process
->pid
);
3985 fprintf (stderr
, "\n");
3988 /* Now we can kill or detach the inferiors. */
3989 for_each_process ([] (process_info
*process
) {
3990 int pid
= process
->pid
;
3992 if (process
->attached
)
3993 detach_inferior (process
);
3995 kill_inferior (process
);
3997 discard_queued_stop_replies (ptid_t (pid
));
4001 /* Value that will be passed to exit(3) when gdbserver exits. */
4002 static int exit_code
;
4004 /* Wrapper for detach_or_kill_for_exit that catches and prints
4008 detach_or_kill_for_exit_cleanup ()
4012 detach_or_kill_for_exit ();
4014 catch (const gdb_exception
&exception
)
4017 fprintf (stderr
, "Detach or kill failed: %s\n",
4025 namespace selftests
{
4028 test_memory_tagging_functions (void)
4030 /* Setup testing. */
4031 gdb::char_vector packet
;
4032 gdb::byte_vector tags
, bv
;
4033 std::string expected
;
4034 packet
.resize (32000);
4039 /* Test parsing a qMemTags request. */
4041 /* Valid request, addr, len and type updated. */
4045 strcpy (packet
.data (), "qMemTags:0,0:0");
4046 parse_fetch_memtags_request (packet
.data (), &addr
, &len
, &type
);
4047 SELF_CHECK (addr
== 0 && len
== 0 && type
== 0);
4049 /* Valid request, addr, len and type updated. */
4053 strcpy (packet
.data (), "qMemTags:deadbeef,ff:5");
4054 parse_fetch_memtags_request (packet
.data (), &addr
, &len
, &type
);
4055 SELF_CHECK (addr
== 0xdeadbeef && len
== 255 && type
== 5);
4057 /* Test creating a qMemTags reply. */
4059 /* Non-empty tag data. */
4062 for (int i
= 0; i
< 5; i
++)
4065 expected
= "m0001020304";
4066 SELF_CHECK (create_fetch_memtags_reply (packet
.data (), bv
) == true);
4067 SELF_CHECK (strcmp (packet
.data (), expected
.c_str ()) == 0);
4069 /* Test parsing a QMemTags request. */
4071 /* Valid request and empty tag data: addr, len, type and tags updated. */
4076 strcpy (packet
.data (), "QMemTags:0,0:0:");
4077 SELF_CHECK (parse_store_memtags_request (packet
.data (),
4078 &addr
, &len
, tags
, &type
) == true);
4079 SELF_CHECK (addr
== 0 && len
== 0 && type
== 0 && tags
.size () == 0);
4081 /* Valid request and non-empty tag data: addr, len, type
4082 and tags updated. */
4087 strcpy (packet
.data (),
4088 "QMemTags:deadbeef,ff:5:0001020304");
4089 SELF_CHECK (parse_store_memtags_request (packet
.data (), &addr
, &len
, tags
,
4091 SELF_CHECK (addr
== 0xdeadbeef && len
== 255 && type
== 5
4092 && tags
.size () == 5);
4095 } // namespace selftests
4096 #endif /* GDB_SELF_TEST */
4098 /* Main function. This is called by the real "main" function,
4099 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
4101 [[noreturn
]] static void
4102 captured_main (int argc
, char *argv
[])
4107 const char *port
= NULL
;
4108 char **next_arg
= &argv
[1];
4109 volatile int multi_mode
= 0;
4110 volatile int attach
= 0;
4112 bool selftest
= false;
4114 std::vector
<const char *> selftest_filters
;
4116 selftests::register_test ("remote_memory_tagging",
4117 selftests::test_memory_tagging_functions
);
4120 current_directory
= getcwd (NULL
, 0);
4121 client_state
&cs
= get_client_state ();
4123 if (current_directory
== NULL
)
4125 error (_("Could not find current working directory: %s"),
4126 safe_strerror (errno
));
4129 while (*next_arg
!= NULL
&& **next_arg
== '-')
4131 if (strcmp (*next_arg
, "--version") == 0)
4133 gdbserver_version ();
4136 else if (strcmp (*next_arg
, "--help") == 0)
4138 gdbserver_usage (stdout
);
4141 else if (strcmp (*next_arg
, "--attach") == 0)
4143 else if (strcmp (*next_arg
, "--multi") == 0)
4145 else if (strcmp (*next_arg
, "--wrapper") == 0)
4152 while (*next_arg
!= NULL
&& strcmp (*next_arg
, "--") != 0)
4154 wrapper_argv
+= *next_arg
;
4155 wrapper_argv
+= ' ';
4159 if (!wrapper_argv
.empty ())
4161 /* Erase the last whitespace. */
4162 wrapper_argv
.erase (wrapper_argv
.end () - 1);
4165 if (next_arg
== tmp
|| *next_arg
== NULL
)
4167 gdbserver_usage (stderr
);
4171 /* Consume the "--". */
4174 else if (startswith (*next_arg
, "--debug="))
4178 parse_debug_options ((*next_arg
) + sizeof ("--debug=") - 1);
4180 catch (const gdb_exception_error
&exception
)
4183 fprintf (stderr
, "gdbserver: %s\n", exception
.what ());
4187 else if (strcmp (*next_arg
, "--debug") == 0)
4191 parse_debug_options ("");
4193 catch (const gdb_exception_error
&exception
)
4196 fprintf (stderr
, "gdbserver: %s\n", exception
.what ());
4200 else if (startswith (*next_arg
, "--debug-format="))
4202 std::string error_msg
4203 = parse_debug_format_options ((*next_arg
)
4204 + sizeof ("--debug-format=") - 1, 0);
4206 if (!error_msg
.empty ())
4208 fprintf (stderr
, "%s", error_msg
.c_str ());
4212 else if (startswith (*next_arg
, "--debug-file="))
4213 debug_set_output ((*next_arg
) + sizeof ("--debug-file=") -1);
4214 else if (strcmp (*next_arg
, "--disable-packet") == 0)
4216 gdbserver_show_disableable (stdout
);
4219 else if (startswith (*next_arg
, "--disable-packet="))
4221 char *packets
= *next_arg
+= sizeof ("--disable-packet=") - 1;
4223 for (char *tok
= strtok_r (packets
, ",", &saveptr
);
4225 tok
= strtok_r (NULL
, ",", &saveptr
))
4227 if (strcmp ("vCont", tok
) == 0)
4228 disable_packet_vCont
= true;
4229 else if (strcmp ("Tthread", tok
) == 0)
4230 disable_packet_Tthread
= true;
4231 else if (strcmp ("qC", tok
) == 0)
4232 disable_packet_qC
= true;
4233 else if (strcmp ("qfThreadInfo", tok
) == 0)
4234 disable_packet_qfThreadInfo
= true;
4235 else if (strcmp ("T", tok
) == 0)
4236 disable_packet_T
= true;
4237 else if (strcmp ("threads", tok
) == 0)
4239 disable_packet_vCont
= true;
4240 disable_packet_Tthread
= true;
4241 disable_packet_qC
= true;
4242 disable_packet_qfThreadInfo
= true;
4246 fprintf (stderr
, "Don't know how to disable \"%s\".\n\n",
4248 gdbserver_show_disableable (stderr
);
4253 else if (strcmp (*next_arg
, "-") == 0)
4255 /* "-" specifies a stdio connection and is a form of port
4257 port
= STDIO_CONNECTION_NAME
;
4259 /* Implying --once here prevents a hang after stdin has been closed. */
4265 else if (strcmp (*next_arg
, "--disable-randomization") == 0)
4266 cs
.disable_randomization
= 1;
4267 else if (strcmp (*next_arg
, "--no-disable-randomization") == 0)
4268 cs
.disable_randomization
= 0;
4269 else if (strcmp (*next_arg
, "--startup-with-shell") == 0)
4270 startup_with_shell
= true;
4271 else if (strcmp (*next_arg
, "--no-startup-with-shell") == 0)
4272 startup_with_shell
= false;
4273 else if (strcmp (*next_arg
, "--once") == 0)
4275 else if (strcmp (*next_arg
, "--selftest") == 0)
4277 else if (startswith (*next_arg
, "--selftest="))
4282 const char *filter
= *next_arg
+ strlen ("--selftest=");
4283 if (*filter
== '\0')
4285 fprintf (stderr
, _("Error: selftest filter is empty.\n"));
4289 selftest_filters
.push_back (filter
);
4294 fprintf (stderr
, "Unknown argument: %s\n", *next_arg
);
4307 if ((port
== NULL
|| (!attach
&& !multi_mode
&& *next_arg
== NULL
))
4310 gdbserver_usage (stderr
);
4314 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
4315 opened by remote_prepare. */
4318 save_original_signals_state (false);
4320 /* We need to know whether the remote connection is stdio before
4321 starting the inferior. Inferiors created in this scenario have
4322 stdin,stdout redirected. So do this here before we call
4325 remote_prepare (port
);
4330 /* --attach used to come after PORT, so allow it there for
4332 if (*next_arg
!= NULL
&& strcmp (*next_arg
, "--attach") == 0)
4339 && (*next_arg
== NULL
4340 || (*next_arg
)[0] == '\0'
4341 || (pid
= strtoul (*next_arg
, &arg_end
, 0)) == 0
4343 || next_arg
[1] != NULL
))
4348 gdbserver_usage (stderr
);
4352 /* Gather information about the environment. */
4353 our_environ
= gdb_environ::from_host_environ ();
4355 initialize_async_io ();
4357 have_job_control ();
4358 if (target_supports_tracepoints ())
4359 initialize_tracepoint ();
4361 mem_buf
= (unsigned char *) xmalloc (PBUFSIZ
);
4366 selftests::run_tests (selftest_filters
);
4368 printf (_("Selftests have been disabled for this build.\n"));
4370 throw_quit ("Quit");
4373 if (pid
== 0 && *next_arg
!= NULL
)
4377 n
= argc
- (next_arg
- argv
);
4378 program_path
.set (next_arg
[0]);
4379 for (i
= 1; i
< n
; i
++)
4380 program_args
.push_back (xstrdup (next_arg
[i
]));
4382 /* Wait till we are at first instruction in program. */
4383 target_create_inferior (program_path
.get (), program_args
);
4385 /* We are now (hopefully) stopped at the first instruction of
4386 the target process. This assumes that the target process was
4387 successfully created. */
4391 if (attach_inferior (pid
) == -1)
4392 error ("Attaching not supported on this target");
4394 /* Otherwise succeeded. */
4398 cs
.last_status
.set_exited (0);
4399 cs
.last_ptid
= minus_one_ptid
;
4402 SCOPE_EXIT
{ detach_or_kill_for_exit_cleanup (); };
4404 /* Don't report shared library events on the initial connection,
4405 even if some libraries are preloaded. Avoids the "stopped by
4406 shared library event" notice on gdb side. */
4407 if (current_thread
!= nullptr)
4408 current_process ()->dlls_changed
= false;
4410 if (cs
.last_status
.kind () == TARGET_WAITKIND_EXITED
4411 || cs
.last_status
.kind () == TARGET_WAITKIND_SIGNALLED
)
4416 if (!was_running
&& !multi_mode
)
4417 error ("No program to debug");
4422 cs
.multi_process
= 0;
4423 cs
.report_fork_events
= 0;
4424 cs
.report_vfork_events
= 0;
4425 cs
.report_exec_events
= 0;
4426 /* Be sure we're out of tfind mode. */
4427 cs
.current_traceframe
= -1;
4428 cs
.cont_thread
= null_ptid
;
4429 cs
.swbreak_feature
= 0;
4430 cs
.hwbreak_feature
= 0;
4431 cs
.vCont_supported
= 0;
4432 cs
.memory_tagging_feature
= false;
4433 cs
.error_message_supported
= false;
4439 /* Wait for events. This will return when all event sources
4440 are removed from the event loop. */
4441 start_event_loop ();
4443 /* If an exit was requested (using the "monitor exit"
4444 command), terminate now. */
4446 throw_quit ("Quit");
4448 /* The only other way to get here is for getpkt to fail:
4450 - If --once was specified, we're done.
4452 - If not in extended-remote mode, and we're no longer
4453 debugging anything, simply exit: GDB has disconnected
4454 after processing the last process exit.
4456 - Otherwise, close the connection and reopen it at the
4458 if (run_once
|| (!extended_protocol
&& !target_running ()))
4459 throw_quit ("Quit");
4462 "Remote side has terminated connection. "
4463 "GDBserver will reopen the connection.\n");
4465 /* Get rid of any pending statuses. An eventual reconnection
4466 (by the same GDB instance or another) will refresh all its
4467 state from scratch. */
4468 discard_queued_stop_replies (minus_one_ptid
);
4469 for_each_thread ([] (thread_info
*thread
)
4471 thread
->status_pending_p
= 0;
4476 if (disconnected_tracing
)
4478 /* Try to enable non-stop/async mode, so we we can
4479 both wait for an async socket accept, and handle
4480 async target events simultaneously. There's also
4481 no point either in having the target always stop
4482 all threads, when we're going to pass signals
4483 down without informing GDB. */
4486 if (the_target
->start_non_stop (true))
4489 /* Detaching implicitly resumes all threads;
4490 simply disconnecting does not. */
4496 "Disconnected tracing disabled; "
4497 "stopping trace run.\n");
4502 catch (const gdb_exception_error
&exception
)
4505 fprintf (stderr
, "gdbserver: %s\n", exception
.what ());
4507 if (response_needed
)
4509 write_enn (cs
.own_buf
);
4510 putpkt (cs
.own_buf
);
4514 throw_quit ("Quit");
4519 /* Main function. */
4522 main (int argc
, char *argv
[])
4524 setlocale (LC_CTYPE
, "");
4528 captured_main (argc
, argv
);
4530 catch (const gdb_exception
&exception
)
4532 if (exception
.reason
== RETURN_ERROR
)
4535 fprintf (stderr
, "%s\n", exception
.what ());
4536 fprintf (stderr
, "Exiting\n");
4543 gdb_assert_not_reached ("captured_main should never return");
4546 /* Process options coming from Z packets for a breakpoint. PACKET is
4547 the packet buffer. *PACKET is updated to point to the first char
4548 after the last processed option. */
4551 process_point_options (struct gdb_breakpoint
*bp
, const char **packet
)
4553 const char *dataptr
= *packet
;
4556 /* Check if data has the correct format. */
4557 if (*dataptr
!= ';')
4564 if (*dataptr
== ';')
4567 if (*dataptr
== 'X')
4569 /* Conditional expression. */
4570 threads_debug_printf ("Found breakpoint condition.");
4571 if (!add_breakpoint_condition (bp
, &dataptr
))
4572 dataptr
= strchrnul (dataptr
, ';');
4574 else if (startswith (dataptr
, "cmds:"))
4576 dataptr
+= strlen ("cmds:");
4577 threads_debug_printf ("Found breakpoint commands %s.", dataptr
);
4578 persist
= (*dataptr
== '1');
4580 if (add_breakpoint_commands (bp
, &dataptr
, persist
))
4581 dataptr
= strchrnul (dataptr
, ';');
4585 fprintf (stderr
, "Unknown token %c, ignoring.\n",
4587 /* Skip tokens until we find one that we recognize. */
4588 dataptr
= strchrnul (dataptr
, ';');
4594 /* Event loop callback that handles a serial event. The first byte in
4595 the serial buffer gets us here. We expect characters to arrive at
4596 a brisk pace, so we read the rest of the packet with a blocking
4600 process_serial_event (void)
4602 client_state
&cs
= get_client_state ();
4608 int new_packet_len
= -1;
4610 disable_async_io ();
4612 response_needed
= false;
4613 packet_len
= getpkt (cs
.own_buf
);
4614 if (packet_len
<= 0)
4617 /* Force an event loop break. */
4620 response_needed
= true;
4622 char ch
= cs
.own_buf
[0];
4626 handle_query (cs
.own_buf
, packet_len
, &new_packet_len
);
4629 handle_general_set (cs
.own_buf
);
4632 handle_detach (cs
.own_buf
);
4635 extended_protocol
= true;
4636 write_ok (cs
.own_buf
);
4639 handle_status (cs
.own_buf
);
4642 if (cs
.own_buf
[1] == 'c' || cs
.own_buf
[1] == 'g' || cs
.own_buf
[1] == 's')
4644 require_running_or_break (cs
.own_buf
);
4646 ptid_t thread_id
= read_ptid (&cs
.own_buf
[2], NULL
);
4648 if (thread_id
== null_ptid
|| thread_id
== minus_one_ptid
)
4649 thread_id
= null_ptid
;
4650 else if (thread_id
.is_pid ())
4652 /* The ptid represents a pid. */
4653 thread_info
*thread
= find_any_thread_of_pid (thread_id
.pid ());
4657 write_enn (cs
.own_buf
);
4661 thread_id
= thread
->id
;
4665 /* The ptid represents a lwp/tid. */
4666 if (find_thread_ptid (thread_id
) == NULL
)
4668 write_enn (cs
.own_buf
);
4673 if (cs
.own_buf
[1] == 'g')
4675 if (thread_id
== null_ptid
)
4677 /* GDB is telling us to choose any thread. Check if
4678 the currently selected thread is still valid. If
4679 it is not, select the first available. */
4680 thread_info
*thread
= find_thread_ptid (cs
.general_thread
);
4682 thread
= get_first_thread ();
4683 thread_id
= thread
->id
;
4686 cs
.general_thread
= thread_id
;
4687 set_desired_thread ();
4688 gdb_assert (current_thread
!= NULL
);
4690 else if (cs
.own_buf
[1] == 'c')
4691 cs
.cont_thread
= thread_id
;
4693 write_ok (cs
.own_buf
);
4697 /* Silently ignore it so that gdb can extend the protocol
4698 without compatibility headaches. */
4699 cs
.own_buf
[0] = '\0';
4703 require_running_or_break (cs
.own_buf
);
4704 if (cs
.current_traceframe
>= 0)
4706 struct regcache
*regcache
4707 = new_register_cache (current_target_desc ());
4709 if (fetch_traceframe_registers (cs
.current_traceframe
,
4711 registers_to_string (regcache
, cs
.own_buf
);
4713 write_enn (cs
.own_buf
);
4714 free_register_cache (regcache
);
4718 struct regcache
*regcache
;
4720 if (!set_desired_thread ())
4721 write_enn (cs
.own_buf
);
4724 regcache
= get_thread_regcache (current_thread
, 1);
4725 registers_to_string (regcache
, cs
.own_buf
);
4730 require_running_or_break (cs
.own_buf
);
4731 if (cs
.current_traceframe
>= 0)
4732 write_enn (cs
.own_buf
);
4735 struct regcache
*regcache
;
4737 if (!set_desired_thread ())
4738 write_enn (cs
.own_buf
);
4741 regcache
= get_thread_regcache (current_thread
, 1);
4742 registers_from_string (regcache
, &cs
.own_buf
[1]);
4743 write_ok (cs
.own_buf
);
4749 require_running_or_break (cs
.own_buf
);
4750 decode_m_packet (&cs
.own_buf
[1], &mem_addr
, &len
);
4751 int res
= gdb_read_memory (mem_addr
, mem_buf
, len
);
4753 write_enn (cs
.own_buf
);
4755 bin2hex (mem_buf
, cs
.own_buf
, res
);
4759 require_running_or_break (cs
.own_buf
);
4760 decode_M_packet (&cs
.own_buf
[1], &mem_addr
, &len
, &mem_buf
);
4761 if (gdb_write_memory (mem_addr
, mem_buf
, len
) == 0)
4762 write_ok (cs
.own_buf
);
4764 write_enn (cs
.own_buf
);
4767 require_running_or_break (cs
.own_buf
);
4768 if (decode_X_packet (&cs
.own_buf
[1], packet_len
- 1,
4769 &mem_addr
, &len
, &mem_buf
) < 0
4770 || gdb_write_memory (mem_addr
, mem_buf
, len
) != 0)
4771 write_enn (cs
.own_buf
);
4773 write_ok (cs
.own_buf
);
4776 require_running_or_break (cs
.own_buf
);
4777 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4778 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4779 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4782 myresume (cs
.own_buf
, 0, signal
);
4785 require_running_or_break (cs
.own_buf
);
4786 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4787 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4788 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4791 myresume (cs
.own_buf
, 1, signal
);
4794 require_running_or_break (cs
.own_buf
);
4796 myresume (cs
.own_buf
, 0, signal
);
4799 require_running_or_break (cs
.own_buf
);
4801 myresume (cs
.own_buf
, 1, signal
);
4803 case 'Z': /* insert_ ... */
4805 case 'z': /* remove_ ... */
4810 char type
= cs
.own_buf
[1];
4812 const int insert
= ch
== 'Z';
4813 const char *p
= &cs
.own_buf
[3];
4815 p
= unpack_varlen_hex (p
, &addr
);
4816 kind
= strtol (p
+ 1, &dataptr
, 16);
4820 struct gdb_breakpoint
*bp
;
4822 bp
= set_gdb_breakpoint (type
, addr
, kind
, &res
);
4827 /* GDB may have sent us a list of *point parameters to
4828 be evaluated on the target's side. Read such list
4829 here. If we already have a list of parameters, GDB
4830 is telling us to drop that list and use this one
4832 clear_breakpoint_conditions_and_commands (bp
);
4833 const char *options
= dataptr
;
4834 process_point_options (bp
, &options
);
4838 res
= delete_gdb_breakpoint (type
, addr
, kind
);
4841 write_ok (cs
.own_buf
);
4844 cs
.own_buf
[0] = '\0';
4846 write_enn (cs
.own_buf
);
4850 response_needed
= false;
4851 if (!target_running ())
4852 /* The packet we received doesn't make sense - but we can't
4853 reply to it, either. */
4856 fprintf (stderr
, "Killing all inferiors\n");
4858 for_each_process (kill_inferior_callback
);
4860 /* When using the extended protocol, we wait with no program
4861 running. The traditional protocol will exit instead. */
4862 if (extended_protocol
)
4864 cs
.last_status
.set_exited (GDB_SIGNAL_KILL
);
4872 require_running_or_break (cs
.own_buf
);
4874 ptid_t thread_id
= read_ptid (&cs
.own_buf
[1], NULL
);
4875 if (find_thread_ptid (thread_id
) == NULL
)
4877 write_enn (cs
.own_buf
);
4881 if (mythread_alive (thread_id
))
4882 write_ok (cs
.own_buf
);
4884 write_enn (cs
.own_buf
);
4888 response_needed
= false;
4890 /* Restarting the inferior is only supported in the extended
4892 if (extended_protocol
)
4894 if (target_running ())
4895 for_each_process (kill_inferior_callback
);
4897 fprintf (stderr
, "GDBserver restarting\n");
4899 /* Wait till we are at 1st instruction in prog. */
4900 if (program_path
.get () != NULL
)
4902 target_create_inferior (program_path
.get (), program_args
);
4904 if (cs
.last_status
.kind () == TARGET_WAITKIND_STOPPED
)
4906 /* Stopped at the first instruction of the target
4908 cs
.general_thread
= cs
.last_ptid
;
4912 /* Something went wrong. */
4913 cs
.general_thread
= null_ptid
;
4918 cs
.last_status
.set_exited (GDB_SIGNAL_KILL
);
4924 /* It is a request we don't understand. Respond with an
4925 empty packet so that gdb knows that we don't support this
4927 cs
.own_buf
[0] = '\0';
4931 /* Extended (long) request. */
4932 handle_v_requests (cs
.own_buf
, packet_len
, &new_packet_len
);
4936 /* It is a request we don't understand. Respond with an empty
4937 packet so that gdb knows that we don't support this
4939 cs
.own_buf
[0] = '\0';
4943 if (new_packet_len
!= -1)
4944 putpkt_binary (cs
.own_buf
, new_packet_len
);
4946 putpkt (cs
.own_buf
);
4948 response_needed
= false;
4956 /* Event-loop callback for serial events. */
4959 handle_serial_event (int err
, gdb_client_data client_data
)
4961 threads_debug_printf ("handling possible serial event");
4963 /* Really handle it. */
4964 if (process_serial_event () < 0)
4966 keep_processing_events
= false;
4970 /* Be sure to not change the selected thread behind GDB's back.
4971 Important in the non-stop mode asynchronous protocol. */
4972 set_desired_thread ();
4975 /* Push a stop notification on the notification queue. */
4978 push_stop_notification (ptid_t ptid
, const target_waitstatus
&status
)
4980 struct vstop_notif
*vstop_notif
= new struct vstop_notif
;
4982 vstop_notif
->status
= status
;
4983 vstop_notif
->ptid
= ptid
;
4984 /* Push Stop notification. */
4985 notif_push (¬if_stop
, vstop_notif
);
4988 /* Event-loop callback for target events. */
4991 handle_target_event (int err
, gdb_client_data client_data
)
4993 client_state
&cs
= get_client_state ();
4994 threads_debug_printf ("handling possible target event");
4996 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
,
4999 if (cs
.last_status
.kind () == TARGET_WAITKIND_NO_RESUMED
)
5001 if (gdb_connected () && report_no_resumed
)
5002 push_stop_notification (null_ptid
, cs
.last_status
);
5004 else if (cs
.last_status
.kind () != TARGET_WAITKIND_IGNORE
)
5006 int pid
= cs
.last_ptid
.pid ();
5007 struct process_info
*process
= find_process_pid (pid
);
5008 int forward_event
= !gdb_connected () || process
->gdb_detached
;
5010 if (cs
.last_status
.kind () == TARGET_WAITKIND_EXITED
5011 || cs
.last_status
.kind () == TARGET_WAITKIND_SIGNALLED
)
5013 mark_breakpoints_out (process
);
5014 target_mourn_inferior (cs
.last_ptid
);
5016 else if (cs
.last_status
.kind () == TARGET_WAITKIND_THREAD_EXITED
)
5020 /* We're reporting this thread as stopped. Update its
5021 "want-stopped" state to what the client wants, until it
5022 gets a new resume action. */
5023 current_thread
->last_resume_kind
= resume_stop
;
5024 current_thread
->last_status
= cs
.last_status
;
5029 if (!target_running ())
5031 /* The last process exited. We're done. */
5035 if (cs
.last_status
.kind () == TARGET_WAITKIND_EXITED
5036 || cs
.last_status
.kind () == TARGET_WAITKIND_SIGNALLED
5037 || cs
.last_status
.kind () == TARGET_WAITKIND_THREAD_EXITED
)
5041 /* A thread stopped with a signal, but gdb isn't
5042 connected to handle it. Pass it down to the
5043 inferior, as if it wasn't being traced. */
5044 enum gdb_signal signal
;
5046 threads_debug_printf ("GDB not connected; forwarding event %d for"
5048 (int) cs
.last_status
.kind (),
5049 target_pid_to_str (cs
.last_ptid
).c_str ());
5051 if (cs
.last_status
.kind () == TARGET_WAITKIND_STOPPED
)
5052 signal
= cs
.last_status
.sig ();
5054 signal
= GDB_SIGNAL_0
;
5055 target_continue (cs
.last_ptid
, signal
);
5060 push_stop_notification (cs
.last_ptid
, cs
.last_status
);
5062 if (cs
.last_status
.kind () == TARGET_WAITKIND_THREAD_EXITED
5063 && !target_any_resumed ())
5065 target_waitstatus ws
;
5066 ws
.set_no_resumed ();
5067 push_stop_notification (null_ptid
, ws
);
5072 /* Be sure to not change the selected thread behind GDB's back.
5073 Important in the non-stop mode asynchronous protocol. */
5074 set_desired_thread ();
5077 /* See gdbsupport/event-loop.h. */
5080 invoke_async_signal_handlers ()
5085 /* See gdbsupport/event-loop.h. */
5088 check_async_event_handlers ()
5093 /* See gdbsupport/errors.h */
5102 /* See gdbsupport/gdb_select.h. */
5105 gdb_select (int n
, fd_set
*readfds
, fd_set
*writefds
,
5106 fd_set
*exceptfds
, struct timeval
*timeout
)
5108 return select (n
, readfds
, writefds
, exceptfds
, timeout
);
5119 } // namespace selftests
5120 #endif /* GDB_SELF_TEST */