1 /* Main code for remote server for GDB.
2 Copyright (C) 1989-2022 Free Software Foundation, Inc.
4 This file is part of GDB.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #include "gdbthread.h"
21 #include "gdbsupport/agent.h"
24 #include "gdbsupport/rsp-low.h"
25 #include "gdbsupport/signals-state-save-restore.h"
31 #include "gdbsupport/gdb_vecs.h"
32 #include "gdbsupport/gdb_wait.h"
33 #include "gdbsupport/btrace-common.h"
34 #include "gdbsupport/filestuff.h"
35 #include "tracepoint.h"
39 #include "gdbsupport/common-inferior.h"
40 #include "gdbsupport/job-control.h"
41 #include "gdbsupport/environ.h"
42 #include "filenames.h"
43 #include "gdbsupport/pathstuff.h"
45 #include "xml-builtin.h"
48 #include "gdbsupport/selftest.h"
49 #include "gdbsupport/scope-exit.h"
50 #include "gdbsupport/gdb_select.h"
51 #include "gdbsupport/scoped_restore.h"
52 #include "gdbsupport/search.h"
54 #define require_running_or_return(BUF) \
55 if (!target_running ()) \
61 #define require_running_or_break(BUF) \
62 if (!target_running ()) \
68 /* String containing the current directory (what getwd would return). */
70 char *current_directory
;
72 /* The environment to pass to the inferior when creating it. */
74 static gdb_environ our_environ
;
78 static bool extended_protocol
;
79 static bool response_needed
;
80 static bool exit_requested
;
82 /* --once: Exit after the first connection has closed. */
85 /* Whether to report TARGET_WAITKIND_NO_RESUMED events. */
86 static bool report_no_resumed
;
88 /* The event loop checks this to decide whether to continue accepting
90 static bool keep_processing_events
= true;
95 /* Set the PROGRAM_PATH. Here we adjust the path of the provided
97 void set (gdb::unique_xmalloc_ptr
<char> &&path
)
99 m_path
= std::move (path
);
101 /* Make sure we're using the absolute path of the inferior when
103 if (!contains_dir_separator (m_path
.get ()))
107 /* Check if the file is in our CWD. If it is, then we prefix
108 its name with CURRENT_DIRECTORY. Otherwise, we leave the
109 name as-is because we'll try searching for it in $PATH. */
110 if (is_regular_file (m_path
.get (), ®_file_errno
))
111 m_path
= gdb_abspath (m_path
.get ());
115 /* Return the PROGRAM_PATH. */
117 { return m_path
.get (); }
120 /* The program name, adjusted if needed. */
121 gdb::unique_xmalloc_ptr
<char> m_path
;
123 static std::vector
<char *> program_args
;
124 static std::string wrapper_argv
;
126 /* The PID of the originally created or attached inferior. Used to
127 send signals to the process when GDB sends us an asynchronous interrupt
128 (user hitting Control-C in the client), and to wait for the child to exit
129 when no longer debugging it. */
131 unsigned long signal_pid
;
133 /* Set if you want to disable optional thread related packets support
134 in gdbserver, for the sake of testing GDB against stubs that don't
136 bool disable_packet_vCont
;
137 bool disable_packet_Tthread
;
138 bool disable_packet_qC
;
139 bool disable_packet_qfThreadInfo
;
140 bool disable_packet_T
;
142 static unsigned char *mem_buf
;
144 /* A sub-class of 'struct notif_event' for stop, holding information
145 relative to a single stop reply. We keep a queue of these to
146 push to GDB in non-stop mode. */
148 struct vstop_notif
: public notif_event
150 /* Thread or process that got the event. */
154 struct target_waitstatus status
;
157 /* The current btrace configuration. This is gdbserver's mirror of GDB's
158 btrace configuration. */
159 static struct btrace_config current_btrace_conf
;
161 /* The client remote protocol state. */
163 static client_state g_client_state
;
168 client_state
&cs
= g_client_state
;
173 /* Put a stop reply to the stop reply queue. */
176 queue_stop_reply (ptid_t ptid
, struct target_waitstatus
*status
)
178 struct vstop_notif
*new_notif
= new struct vstop_notif
;
180 new_notif
->ptid
= ptid
;
181 new_notif
->status
= *status
;
183 notif_event_enque (¬if_stop
, new_notif
);
187 remove_all_on_match_ptid (struct notif_event
*event
, ptid_t filter_ptid
)
189 struct vstop_notif
*vstop_event
= (struct vstop_notif
*) event
;
191 return vstop_event
->ptid
.matches (filter_ptid
);
197 discard_queued_stop_replies (ptid_t ptid
)
199 std::list
<notif_event
*>::iterator iter
, next
, end
;
200 end
= notif_stop
.queue
.end ();
201 for (iter
= notif_stop
.queue
.begin (); iter
!= end
; iter
= next
)
206 if (iter
== notif_stop
.queue
.begin ())
208 /* The head of the list contains the notification that was
209 already sent to GDB. So we can't remove it, otherwise
210 when GDB sends the vStopped, it would ack the _next_
211 notification, which hadn't been sent yet! */
215 if (remove_all_on_match_ptid (*iter
, ptid
))
218 notif_stop
.queue
.erase (iter
);
224 vstop_notif_reply (struct notif_event
*event
, char *own_buf
)
226 struct vstop_notif
*vstop
= (struct vstop_notif
*) event
;
228 prepare_resume_reply (own_buf
, vstop
->ptid
, &vstop
->status
);
231 /* Helper for in_queued_stop_replies. */
234 in_queued_stop_replies_ptid (struct notif_event
*event
, ptid_t filter_ptid
)
236 struct vstop_notif
*vstop_event
= (struct vstop_notif
*) event
;
238 if (vstop_event
->ptid
.matches (filter_ptid
))
241 /* Don't resume fork children that GDB does not know about yet. */
242 if ((vstop_event
->status
.kind
== TARGET_WAITKIND_FORKED
243 || vstop_event
->status
.kind
== TARGET_WAITKIND_VFORKED
)
244 && vstop_event
->status
.value
.related_pid
.matches (filter_ptid
))
253 in_queued_stop_replies (ptid_t ptid
)
255 for (notif_event
*event
: notif_stop
.queue
)
257 if (in_queued_stop_replies_ptid (event
, ptid
))
264 struct notif_server notif_stop
=
266 "vStopped", "Stop", {}, vstop_notif_reply
,
270 target_running (void)
272 return get_first_thread () != NULL
;
275 /* See gdbsupport/common-inferior.h. */
280 return !wrapper_argv
.empty () ? wrapper_argv
.c_str () : NULL
;
283 /* See gdbsupport/common-inferior.h. */
286 get_exec_file (int err
)
288 if (err
&& program_path
.get () == NULL
)
289 error (_("No executable file specified."));
291 return program_path
.get ();
303 attach_inferior (int pid
)
305 client_state
&cs
= get_client_state ();
306 /* myattach should return -1 if attaching is unsupported,
307 0 if it succeeded, and call error() otherwise. */
309 if (find_process_pid (pid
) != nullptr)
310 error ("Already attached to process %d\n", pid
);
312 if (myattach (pid
) != 0)
315 fprintf (stderr
, "Attached; pid = %d\n", pid
);
318 /* FIXME - It may be that we should get the SIGNAL_PID from the
319 attach function, so that it can be the main thread instead of
320 whichever we were told to attach to. */
325 cs
.last_ptid
= mywait (ptid_t (pid
), &cs
.last_status
, 0, 0);
327 /* GDB knows to ignore the first SIGSTOP after attaching to a running
328 process using the "attach" command, but this is different; it's
329 just using "target remote". Pretend it's just starting up. */
330 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
331 && cs
.last_status
.value
.sig
== GDB_SIGNAL_STOP
)
332 cs
.last_status
.value
.sig
= GDB_SIGNAL_TRAP
;
334 current_thread
->last_resume_kind
= resume_stop
;
335 current_thread
->last_status
= cs
.last_status
;
341 /* Decode a qXfer read request. Return 0 if everything looks OK,
345 decode_xfer_read (char *buf
, CORE_ADDR
*ofs
, unsigned int *len
)
347 /* After the read marker and annex, qXfer looks like a
348 traditional 'm' packet. */
349 decode_m_packet (buf
, ofs
, len
);
355 decode_xfer (char *buf
, char **object
, char **rw
, char **annex
, char **offset
)
357 /* Extract and NUL-terminate the object. */
359 while (*buf
&& *buf
!= ':')
365 /* Extract and NUL-terminate the read/write action. */
367 while (*buf
&& *buf
!= ':')
373 /* Extract and NUL-terminate the annex. */
375 while (*buf
&& *buf
!= ':')
385 /* Write the response to a successful qXfer read. Returns the
386 length of the (binary) data stored in BUF, corresponding
387 to as much of DATA/LEN as we could fit. IS_MORE controls
388 the first character of the response. */
390 write_qxfer_response (char *buf
, const gdb_byte
*data
, int len
, int is_more
)
399 return remote_escape_output (data
, len
, 1, (unsigned char *) buf
+ 1,
400 &out_len
, PBUFSIZ
- 2) + 1;
403 /* Handle btrace enabling in BTS format. */
406 handle_btrace_enable_bts (struct thread_info
*thread
)
408 if (thread
->btrace
!= NULL
)
409 error (_("Btrace already enabled."));
411 current_btrace_conf
.format
= BTRACE_FORMAT_BTS
;
412 thread
->btrace
= target_enable_btrace (thread
->id
, ¤t_btrace_conf
);
415 /* Handle btrace enabling in Intel Processor Trace format. */
418 handle_btrace_enable_pt (struct thread_info
*thread
)
420 if (thread
->btrace
!= NULL
)
421 error (_("Btrace already enabled."));
423 current_btrace_conf
.format
= BTRACE_FORMAT_PT
;
424 thread
->btrace
= target_enable_btrace (thread
->id
, ¤t_btrace_conf
);
427 /* Handle btrace disabling. */
430 handle_btrace_disable (struct thread_info
*thread
)
433 if (thread
->btrace
== NULL
)
434 error (_("Branch tracing not enabled."));
436 if (target_disable_btrace (thread
->btrace
) != 0)
437 error (_("Could not disable branch tracing."));
439 thread
->btrace
= NULL
;
442 /* Handle the "Qbtrace" packet. */
445 handle_btrace_general_set (char *own_buf
)
447 client_state
&cs
= get_client_state ();
448 struct thread_info
*thread
;
451 if (!startswith (own_buf
, "Qbtrace:"))
454 op
= own_buf
+ strlen ("Qbtrace:");
456 if (cs
.general_thread
== null_ptid
457 || cs
.general_thread
== minus_one_ptid
)
459 strcpy (own_buf
, "E.Must select a single thread.");
463 thread
= find_thread_ptid (cs
.general_thread
);
466 strcpy (own_buf
, "E.No such thread.");
472 if (strcmp (op
, "bts") == 0)
473 handle_btrace_enable_bts (thread
);
474 else if (strcmp (op
, "pt") == 0)
475 handle_btrace_enable_pt (thread
);
476 else if (strcmp (op
, "off") == 0)
477 handle_btrace_disable (thread
);
479 error (_("Bad Qbtrace operation. Use bts, pt, or off."));
483 catch (const gdb_exception_error
&exception
)
485 sprintf (own_buf
, "E.%s", exception
.what ());
491 /* Handle the "Qbtrace-conf" packet. */
494 handle_btrace_conf_general_set (char *own_buf
)
496 client_state
&cs
= get_client_state ();
497 struct thread_info
*thread
;
500 if (!startswith (own_buf
, "Qbtrace-conf:"))
503 op
= own_buf
+ strlen ("Qbtrace-conf:");
505 if (cs
.general_thread
== null_ptid
506 || cs
.general_thread
== minus_one_ptid
)
508 strcpy (own_buf
, "E.Must select a single thread.");
512 thread
= find_thread_ptid (cs
.general_thread
);
515 strcpy (own_buf
, "E.No such thread.");
519 if (startswith (op
, "bts:size="))
525 size
= strtoul (op
+ strlen ("bts:size="), &endp
, 16);
526 if (endp
== NULL
|| *endp
!= 0 || errno
!= 0 || size
> UINT_MAX
)
528 strcpy (own_buf
, "E.Bad size value.");
532 current_btrace_conf
.bts
.size
= (unsigned int) size
;
534 else if (strncmp (op
, "pt:size=", strlen ("pt:size=")) == 0)
540 size
= strtoul (op
+ strlen ("pt:size="), &endp
, 16);
541 if (endp
== NULL
|| *endp
!= 0 || errno
!= 0 || size
> UINT_MAX
)
543 strcpy (own_buf
, "E.Bad size value.");
547 current_btrace_conf
.pt
.size
= (unsigned int) size
;
551 strcpy (own_buf
, "E.Bad Qbtrace configuration option.");
559 /* Create the qMemTags packet reply given TAGS.
561 Returns true if parsing succeeded and false otherwise. */
564 create_fetch_memtags_reply (char *reply
, const gdb::byte_vector
&tags
)
566 /* It is an error to pass a zero-sized tag vector. */
567 gdb_assert (tags
.size () != 0);
569 std::string
packet ("m");
571 /* Write the tag data. */
572 packet
+= bin2hex (tags
.data (), tags
.size ());
574 /* Check if the reply is too big for the packet to handle. */
575 if (PBUFSIZ
< packet
.size ())
578 strcpy (reply
, packet
.c_str ());
582 /* Parse the QMemTags request into ADDR, LEN and TAGS.
584 Returns true if parsing succeeded and false otherwise. */
587 parse_store_memtags_request (char *request
, CORE_ADDR
*addr
, size_t *len
,
588 gdb::byte_vector
&tags
, int *type
)
590 gdb_assert (startswith (request
, "QMemTags:"));
592 const char *p
= request
+ strlen ("QMemTags:");
594 /* Read address and length. */
595 unsigned int length
= 0;
596 p
= decode_m_packet_params (p
, addr
, &length
, ':');
599 /* Read the tag type. */
600 ULONGEST tag_type
= 0;
601 p
= unpack_varlen_hex (p
, &tag_type
);
602 *type
= (int) tag_type
;
604 /* Make sure there is a colon after the type. */
608 /* Skip the colon. */
611 /* Read the tag data. */
617 /* Handle all of the extended 'Q' packets. */
620 handle_general_set (char *own_buf
)
622 client_state
&cs
= get_client_state ();
623 if (startswith (own_buf
, "QPassSignals:"))
625 int numsigs
= (int) GDB_SIGNAL_LAST
, i
;
626 const char *p
= own_buf
+ strlen ("QPassSignals:");
629 p
= decode_address_to_semicolon (&cursig
, p
);
630 for (i
= 0; i
< numsigs
; i
++)
634 cs
.pass_signals
[i
] = 1;
636 /* Keep looping, to clear the remaining signals. */
639 p
= decode_address_to_semicolon (&cursig
, p
);
642 cs
.pass_signals
[i
] = 0;
644 strcpy (own_buf
, "OK");
648 if (startswith (own_buf
, "QProgramSignals:"))
650 int numsigs
= (int) GDB_SIGNAL_LAST
, i
;
651 const char *p
= own_buf
+ strlen ("QProgramSignals:");
654 cs
.program_signals_p
= 1;
656 p
= decode_address_to_semicolon (&cursig
, p
);
657 for (i
= 0; i
< numsigs
; i
++)
661 cs
.program_signals
[i
] = 1;
663 /* Keep looping, to clear the remaining signals. */
666 p
= decode_address_to_semicolon (&cursig
, p
);
669 cs
.program_signals
[i
] = 0;
671 strcpy (own_buf
, "OK");
675 if (startswith (own_buf
, "QCatchSyscalls:"))
677 const char *p
= own_buf
+ sizeof ("QCatchSyscalls:") - 1;
680 struct process_info
*process
;
682 if (!target_running () || !target_supports_catch_syscall ())
688 if (strcmp (p
, "0") == 0)
690 else if (p
[0] == '1' && (p
[1] == ';' || p
[1] == '\0'))
694 fprintf (stderr
, "Unknown catch-syscalls mode requested: %s\n",
700 process
= current_process ();
701 process
->syscalls_to_catch
.clear ();
711 p
= decode_address_to_semicolon (&sysno
, p
);
712 process
->syscalls_to_catch
.push_back (sysno
);
716 process
->syscalls_to_catch
.push_back (ANY_SYSCALL
);
723 if (strcmp (own_buf
, "QEnvironmentReset") == 0)
725 our_environ
= gdb_environ::from_host_environ ();
731 if (startswith (own_buf
, "QEnvironmentHexEncoded:"))
733 const char *p
= own_buf
+ sizeof ("QEnvironmentHexEncoded:") - 1;
734 /* The final form of the environment variable. FINAL_VAR will
735 hold the 'VAR=VALUE' format. */
736 std::string final_var
= hex2str (p
);
737 std::string var_name
, var_value
;
741 debug_printf (_("[QEnvironmentHexEncoded received '%s']\n"), p
);
742 debug_printf (_("[Environment variable to be set: '%s']\n"),
747 size_t pos
= final_var
.find ('=');
748 if (pos
== std::string::npos
)
750 warning (_("Unexpected format for environment variable: '%s'"),
756 var_name
= final_var
.substr (0, pos
);
757 var_value
= final_var
.substr (pos
+ 1, std::string::npos
);
759 our_environ
.set (var_name
.c_str (), var_value
.c_str ());
765 if (startswith (own_buf
, "QEnvironmentUnset:"))
767 const char *p
= own_buf
+ sizeof ("QEnvironmentUnset:") - 1;
768 std::string varname
= hex2str (p
);
772 debug_printf (_("[QEnvironmentUnset received '%s']\n"), p
);
773 debug_printf (_("[Environment variable to be unset: '%s']\n"),
778 our_environ
.unset (varname
.c_str ());
784 if (strcmp (own_buf
, "QStartNoAckMode") == 0)
788 debug_printf ("[noack mode enabled]\n");
797 if (startswith (own_buf
, "QNonStop:"))
799 char *mode
= own_buf
+ 9;
803 if (strcmp (mode
, "0") == 0)
805 else if (strcmp (mode
, "1") == 0)
809 /* We don't know what this mode is, so complain to
811 fprintf (stderr
, "Unknown non-stop mode requested: %s\n",
817 req_str
= req
? "non-stop" : "all-stop";
818 if (the_target
->start_non_stop (req
== 1) != 0)
820 fprintf (stderr
, "Setting %s mode failed\n", req_str
);
825 non_stop
= (req
!= 0);
828 debug_printf ("[%s mode enabled]\n", req_str
);
834 if (startswith (own_buf
, "QDisableRandomization:"))
836 char *packet
= own_buf
+ strlen ("QDisableRandomization:");
839 unpack_varlen_hex (packet
, &setting
);
840 cs
.disable_randomization
= setting
;
844 debug_printf (cs
.disable_randomization
845 ? "[address space randomization disabled]\n"
846 : "[address space randomization enabled]\n");
853 if (target_supports_tracepoints ()
854 && handle_tracepoint_general_set (own_buf
))
857 if (startswith (own_buf
, "QAgent:"))
859 char *mode
= own_buf
+ strlen ("QAgent:");
862 if (strcmp (mode
, "0") == 0)
864 else if (strcmp (mode
, "1") == 0)
868 /* We don't know what this value is, so complain to GDB. */
869 sprintf (own_buf
, "E.Unknown QAgent value");
873 /* Update the flag. */
876 debug_printf ("[%s agent]\n", req
? "Enable" : "Disable");
881 if (handle_btrace_general_set (own_buf
))
884 if (handle_btrace_conf_general_set (own_buf
))
887 if (startswith (own_buf
, "QThreadEvents:"))
889 char *mode
= own_buf
+ strlen ("QThreadEvents:");
890 enum tribool req
= TRIBOOL_UNKNOWN
;
892 if (strcmp (mode
, "0") == 0)
894 else if (strcmp (mode
, "1") == 0)
898 /* We don't know what this mode is, so complain to GDB. */
900 = string_printf ("E.Unknown thread-events mode requested: %s\n",
902 strcpy (own_buf
, err
.c_str ());
906 cs
.report_thread_events
= (req
== TRIBOOL_TRUE
);
910 const char *req_str
= cs
.report_thread_events
? "enabled" : "disabled";
912 debug_printf ("[thread events are now %s]\n", req_str
);
919 if (startswith (own_buf
, "QStartupWithShell:"))
921 const char *value
= own_buf
+ strlen ("QStartupWithShell:");
923 if (strcmp (value
, "1") == 0)
924 startup_with_shell
= true;
925 else if (strcmp (value
, "0") == 0)
926 startup_with_shell
= false;
930 fprintf (stderr
, "Unknown value to startup-with-shell: %s\n",
937 debug_printf (_("[Inferior will %s started with shell]"),
938 startup_with_shell
? "be" : "not be");
944 if (startswith (own_buf
, "QSetWorkingDir:"))
946 const char *p
= own_buf
+ strlen ("QSetWorkingDir:");
950 std::string path
= hex2str (p
);
952 set_inferior_cwd (path
.c_str ());
955 debug_printf (_("[Set the inferior's current directory to %s]\n"),
960 /* An empty argument means that we should clear out any
961 previously set cwd for the inferior. */
962 set_inferior_cwd (NULL
);
966 [Unset the inferior's current directory; will use gdbserver's cwd]\n"));
974 /* Handle store memory tags packets. */
975 if (startswith (own_buf
, "QMemTags:")
976 && target_supports_memory_tagging ())
978 gdb::byte_vector tags
;
983 require_running_or_return (own_buf
);
985 bool ret
= parse_store_memtags_request (own_buf
, &addr
, &len
, tags
,
989 ret
= the_target
->store_memtags (addr
, len
, tags
, type
);
999 /* Otherwise we didn't know what packet it was. Say we didn't
1005 get_features_xml (const char *annex
)
1007 const struct target_desc
*desc
= current_target_desc ();
1009 /* `desc->xmltarget' defines what to return when looking for the
1010 "target.xml" file. Its contents can either be verbatim XML code
1011 (prefixed with a '@') or else the name of the actual XML file to
1012 be used in place of "target.xml".
1014 This variable is set up from the auto-generated
1015 init_registers_... routine for the current target. */
1017 if (strcmp (annex
, "target.xml") == 0)
1019 const char *ret
= tdesc_get_features_xml (desc
);
1031 /* Look for the annex. */
1032 for (i
= 0; xml_builtin
[i
][0] != NULL
; i
++)
1033 if (strcmp (annex
, xml_builtin
[i
][0]) == 0)
1036 if (xml_builtin
[i
][0] != NULL
)
1037 return xml_builtin
[i
][1];
1045 monitor_show_help (void)
1047 monitor_output ("The following monitor commands are supported:\n");
1048 monitor_output (" set debug <0|1>\n");
1049 monitor_output (" Enable general debugging messages\n");
1050 monitor_output (" set debug-hw-points <0|1>\n");
1051 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
1052 monitor_output (" set remote-debug <0|1>\n");
1053 monitor_output (" Enable remote protocol debugging messages\n");
1054 monitor_output (" set event-loop-debug <0|1>\n");
1055 monitor_output (" Enable event loop debugging messages\n");
1056 monitor_output (" set debug-format option1[,option2,...]\n");
1057 monitor_output (" Add additional information to debugging messages\n");
1058 monitor_output (" Options: all, none");
1059 monitor_output (", timestamp");
1060 monitor_output ("\n");
1061 monitor_output (" exit\n");
1062 monitor_output (" Quit GDBserver\n");
1065 /* Read trace frame or inferior memory. Returns the number of bytes
1066 actually read, zero when no further transfer is possible, and -1 on
1067 error. Return of a positive value smaller than LEN does not
1068 indicate there's no more to be read, only the end of the transfer.
1069 E.g., when GDB reads memory from a traceframe, a first request may
1070 be served from a memory block that does not cover the whole request
1071 length. A following request gets the rest served from either
1072 another block (of the same traceframe) or from the read-only
1076 gdb_read_memory (CORE_ADDR memaddr
, unsigned char *myaddr
, int len
)
1078 client_state
&cs
= get_client_state ();
1081 if (cs
.current_traceframe
>= 0)
1084 ULONGEST length
= len
;
1086 if (traceframe_read_mem (cs
.current_traceframe
,
1087 memaddr
, myaddr
, len
, &nbytes
))
1089 /* Data read from trace buffer, we're done. */
1092 if (!in_readonly_region (memaddr
, length
))
1094 /* Otherwise we have a valid readonly case, fall through. */
1095 /* (assume no half-trace half-real blocks for now) */
1098 res
= prepare_to_access_memory ();
1101 if (set_desired_thread ())
1102 res
= read_inferior_memory (memaddr
, myaddr
, len
);
1105 done_accessing_memory ();
1107 return res
== 0 ? len
: -1;
1113 /* Write trace frame or inferior memory. Actually, writing to trace
1114 frames is forbidden. */
1117 gdb_write_memory (CORE_ADDR memaddr
, const unsigned char *myaddr
, int len
)
1119 client_state
&cs
= get_client_state ();
1120 if (cs
.current_traceframe
>= 0)
1126 ret
= prepare_to_access_memory ();
1129 if (set_desired_thread ())
1130 ret
= target_write_memory (memaddr
, myaddr
, len
);
1133 done_accessing_memory ();
1139 /* Handle qSearch:memory packets. */
1142 handle_search_memory (char *own_buf
, int packet_len
)
1144 CORE_ADDR start_addr
;
1145 CORE_ADDR search_space_len
;
1147 unsigned int pattern_len
;
1149 CORE_ADDR found_addr
;
1150 int cmd_name_len
= sizeof ("qSearch:memory:") - 1;
1152 pattern
= (gdb_byte
*) malloc (packet_len
);
1153 if (pattern
== NULL
)
1154 error ("Unable to allocate memory to perform the search");
1156 if (decode_search_memory_packet (own_buf
+ cmd_name_len
,
1157 packet_len
- cmd_name_len
,
1158 &start_addr
, &search_space_len
,
1159 pattern
, &pattern_len
) < 0)
1162 error ("Error in parsing qSearch:memory packet");
1165 auto read_memory
= [] (CORE_ADDR addr
, gdb_byte
*result
, size_t len
)
1167 return gdb_read_memory (addr
, result
, len
) == len
;
1170 found
= simple_search_memory (read_memory
, start_addr
, search_space_len
,
1171 pattern
, pattern_len
, &found_addr
);
1174 sprintf (own_buf
, "1,%lx", (long) found_addr
);
1175 else if (found
== 0)
1176 strcpy (own_buf
, "0");
1178 strcpy (own_buf
, "E00");
1183 /* Handle the "D" packet. */
1186 handle_detach (char *own_buf
)
1188 client_state
&cs
= get_client_state ();
1190 process_info
*process
;
1192 if (cs
.multi_process
)
1195 int pid
= strtol (&own_buf
[2], NULL
, 16);
1197 process
= find_process_pid (pid
);
1201 process
= (current_thread
!= nullptr
1202 ? get_thread_process (current_thread
)
1206 if (process
== NULL
)
1208 write_enn (own_buf
);
1212 if ((tracing
&& disconnected_tracing
) || any_persistent_commands (process
))
1214 if (tracing
&& disconnected_tracing
)
1216 "Disconnected tracing in effect, "
1217 "leaving gdbserver attached to the process\n");
1219 if (any_persistent_commands (process
))
1221 "Persistent commands are present, "
1222 "leaving gdbserver attached to the process\n");
1224 /* Make sure we're in non-stop/async mode, so we we can both
1225 wait for an async socket accept, and handle async target
1226 events simultaneously. There's also no point either in
1227 having the target stop all threads, when we're going to
1228 pass signals down without informing GDB. */
1232 debug_printf ("Forcing non-stop mode\n");
1235 the_target
->start_non_stop (true);
1238 process
->gdb_detached
= 1;
1240 /* Detaching implicitly resumes all threads. */
1241 target_continue_no_signal (minus_one_ptid
);
1247 fprintf (stderr
, "Detaching from process %d\n", process
->pid
);
1250 /* We'll need this after PROCESS has been destroyed. */
1251 int pid
= process
->pid
;
1253 if (detach_inferior (process
) != 0)
1254 write_enn (own_buf
);
1257 discard_queued_stop_replies (ptid_t (pid
));
1260 if (extended_protocol
|| target_running ())
1262 /* There is still at least one inferior remaining or
1263 we are in extended mode, so don't terminate gdbserver,
1264 and instead treat this like a normal program exit. */
1265 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
1266 cs
.last_status
.value
.integer
= 0;
1267 cs
.last_ptid
= ptid_t (pid
);
1269 current_thread
= NULL
;
1276 /* If we are attached, then we can exit. Otherwise, we
1277 need to hang around doing nothing, until the child is
1279 join_inferior (pid
);
1285 /* Parse options to --debug-format= and "monitor set debug-format".
1286 ARG is the text after "--debug-format=" or "monitor set debug-format".
1287 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1288 This triggers calls to monitor_output.
1289 The result is an empty string if all options were parsed ok, otherwise an
1290 error message which the caller must free.
1292 N.B. These commands affect all debug format settings, they are not
1293 cumulative. If a format is not specified, it is turned off.
1294 However, we don't go to extra trouble with things like
1295 "monitor set debug-format all,none,timestamp".
1296 Instead we just parse them one at a time, in order.
1298 The syntax for "monitor set debug" we support here is not identical
1299 to gdb's "set debug foo on|off" because we also use this function to
1300 parse "--debug-format=foo,bar". */
1303 parse_debug_format_options (const char *arg
, int is_monitor
)
1305 /* First turn all debug format options off. */
1306 debug_timestamp
= 0;
1308 /* First remove leading spaces, for "monitor set debug-format". */
1309 while (isspace (*arg
))
1312 std::vector
<gdb::unique_xmalloc_ptr
<char>> options
1313 = delim_string_to_char_ptr_vec (arg
, ',');
1315 for (const gdb::unique_xmalloc_ptr
<char> &option
: options
)
1317 if (strcmp (option
.get (), "all") == 0)
1319 debug_timestamp
= 1;
1321 monitor_output ("All extra debug format options enabled.\n");
1323 else if (strcmp (option
.get (), "none") == 0)
1325 debug_timestamp
= 0;
1327 monitor_output ("All extra debug format options disabled.\n");
1329 else if (strcmp (option
.get (), "timestamp") == 0)
1331 debug_timestamp
= 1;
1333 monitor_output ("Timestamps will be added to debug output.\n");
1335 else if (*option
== '\0')
1337 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1341 return string_printf ("Unknown debug-format argument: \"%s\"\n",
1345 return std::string ();
1348 /* Handle monitor commands not handled by target-specific handlers. */
1351 handle_monitor_command (char *mon
, char *own_buf
)
1353 if (strcmp (mon
, "set debug 1") == 0)
1356 monitor_output ("Debug output enabled.\n");
1358 else if (strcmp (mon
, "set debug 0") == 0)
1361 monitor_output ("Debug output disabled.\n");
1363 else if (strcmp (mon
, "set debug-hw-points 1") == 0)
1365 show_debug_regs
= 1;
1366 monitor_output ("H/W point debugging output enabled.\n");
1368 else if (strcmp (mon
, "set debug-hw-points 0") == 0)
1370 show_debug_regs
= 0;
1371 monitor_output ("H/W point debugging output disabled.\n");
1373 else if (strcmp (mon
, "set remote-debug 1") == 0)
1376 monitor_output ("Protocol debug output enabled.\n");
1378 else if (strcmp (mon
, "set remote-debug 0") == 0)
1381 monitor_output ("Protocol debug output disabled.\n");
1383 else if (strcmp (mon
, "set event-loop-debug 1") == 0)
1385 debug_event_loop
= debug_event_loop_kind::ALL
;
1386 monitor_output ("Event loop debug output enabled.\n");
1388 else if (strcmp (mon
, "set event-loop-debug 0") == 0)
1390 debug_event_loop
= debug_event_loop_kind::OFF
;
1391 monitor_output ("Event loop debug output disabled.\n");
1393 else if (startswith (mon
, "set debug-format "))
1395 std::string error_msg
1396 = parse_debug_format_options (mon
+ sizeof ("set debug-format ") - 1,
1399 if (!error_msg
.empty ())
1401 monitor_output (error_msg
.c_str ());
1402 monitor_show_help ();
1403 write_enn (own_buf
);
1406 else if (strcmp (mon
, "set debug-file") == 0)
1407 debug_set_output (nullptr);
1408 else if (startswith (mon
, "set debug-file "))
1409 debug_set_output (mon
+ sizeof ("set debug-file ") - 1);
1410 else if (strcmp (mon
, "help") == 0)
1411 monitor_show_help ();
1412 else if (strcmp (mon
, "exit") == 0)
1413 exit_requested
= true;
1416 monitor_output ("Unknown monitor command.\n\n");
1417 monitor_show_help ();
1418 write_enn (own_buf
);
1422 /* Associates a callback with each supported qXfer'able object. */
1426 /* The object this handler handles. */
1429 /* Request that the target transfer up to LEN 8-bit bytes of the
1430 target's OBJECT. The OFFSET, for a seekable object, specifies
1431 the starting point. The ANNEX can be used to provide additional
1432 data-specific information to the target.
1434 Return the number of bytes actually transfered, zero when no
1435 further transfer is possible, -1 on error, -2 when the transfer
1436 is not supported, and -3 on a verbose error message that should
1437 be preserved. Return of a positive value smaller than LEN does
1438 not indicate the end of the object, only the end of the transfer.
1440 One, and only one, of readbuf or writebuf must be non-NULL. */
1441 int (*xfer
) (const char *annex
,
1442 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1443 ULONGEST offset
, LONGEST len
);
1446 /* Handle qXfer:auxv:read. */
1449 handle_qxfer_auxv (const char *annex
,
1450 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1451 ULONGEST offset
, LONGEST len
)
1453 if (!the_target
->supports_read_auxv () || writebuf
!= NULL
)
1456 if (annex
[0] != '\0' || current_thread
== NULL
)
1459 return the_target
->read_auxv (offset
, readbuf
, len
);
1462 /* Handle qXfer:exec-file:read. */
1465 handle_qxfer_exec_file (const char *annex
,
1466 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1467 ULONGEST offset
, LONGEST len
)
1472 if (!the_target
->supports_pid_to_exec_file () || writebuf
!= NULL
)
1475 if (annex
[0] == '\0')
1477 if (current_thread
== NULL
)
1480 pid
= pid_of (current_thread
);
1484 annex
= unpack_varlen_hex (annex
, &pid
);
1485 if (annex
[0] != '\0')
1492 const char *file
= the_target
->pid_to_exec_file (pid
);
1496 total_len
= strlen (file
);
1498 if (offset
> total_len
)
1501 if (offset
+ len
> total_len
)
1502 len
= total_len
- offset
;
1504 memcpy (readbuf
, file
+ offset
, len
);
1508 /* Handle qXfer:features:read. */
1511 handle_qxfer_features (const char *annex
,
1512 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1513 ULONGEST offset
, LONGEST len
)
1515 const char *document
;
1518 if (writebuf
!= NULL
)
1521 if (!target_running ())
1524 /* Grab the correct annex. */
1525 document
= get_features_xml (annex
);
1526 if (document
== NULL
)
1529 total_len
= strlen (document
);
1531 if (offset
> total_len
)
1534 if (offset
+ len
> total_len
)
1535 len
= total_len
- offset
;
1537 memcpy (readbuf
, document
+ offset
, len
);
1541 /* Handle qXfer:libraries:read. */
1544 handle_qxfer_libraries (const char *annex
,
1545 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1546 ULONGEST offset
, LONGEST len
)
1548 if (writebuf
!= NULL
)
1551 if (annex
[0] != '\0' || current_thread
== NULL
)
1554 std::string document
= "<library-list version=\"1.0\">\n";
1556 process_info
*proc
= current_process ();
1557 for (const dll_info
&dll
: proc
->all_dlls
)
1558 document
+= string_printf
1559 (" <library name=\"%s\"><segment address=\"0x%s\"/></library>\n",
1560 dll
.name
.c_str (), paddress (dll
.base_addr
));
1562 document
+= "</library-list>\n";
1564 if (offset
> document
.length ())
1567 if (offset
+ len
> document
.length ())
1568 len
= document
.length () - offset
;
1570 memcpy (readbuf
, &document
[offset
], len
);
1575 /* Handle qXfer:libraries-svr4:read. */
1578 handle_qxfer_libraries_svr4 (const char *annex
,
1579 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1580 ULONGEST offset
, LONGEST len
)
1582 if (writebuf
!= NULL
)
1585 if (current_thread
== NULL
1586 || !the_target
->supports_qxfer_libraries_svr4 ())
1589 return the_target
->qxfer_libraries_svr4 (annex
, readbuf
, writebuf
,
1593 /* Handle qXfer:osadata:read. */
1596 handle_qxfer_osdata (const char *annex
,
1597 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1598 ULONGEST offset
, LONGEST len
)
1600 if (!the_target
->supports_qxfer_osdata () || writebuf
!= NULL
)
1603 return the_target
->qxfer_osdata (annex
, readbuf
, NULL
, offset
, len
);
1606 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1609 handle_qxfer_siginfo (const char *annex
,
1610 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1611 ULONGEST offset
, LONGEST len
)
1613 if (!the_target
->supports_qxfer_siginfo ())
1616 if (annex
[0] != '\0' || current_thread
== NULL
)
1619 return the_target
->qxfer_siginfo (annex
, readbuf
, writebuf
, offset
, len
);
1622 /* Handle qXfer:statictrace:read. */
1625 handle_qxfer_statictrace (const char *annex
,
1626 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1627 ULONGEST offset
, LONGEST len
)
1629 client_state
&cs
= get_client_state ();
1632 if (writebuf
!= NULL
)
1635 if (annex
[0] != '\0' || current_thread
== NULL
1636 || cs
.current_traceframe
== -1)
1639 if (traceframe_read_sdata (cs
.current_traceframe
, offset
,
1640 readbuf
, len
, &nbytes
))
1645 /* Helper for handle_qxfer_threads_proper.
1646 Emit the XML to describe the thread of INF. */
1649 handle_qxfer_threads_worker (thread_info
*thread
, struct buffer
*buffer
)
1651 ptid_t ptid
= ptid_of (thread
);
1653 int core
= target_core_of_thread (ptid
);
1655 const char *name
= target_thread_name (ptid
);
1658 bool handle_status
= target_thread_handle (ptid
, &handle
, &handle_len
);
1660 /* If this is a fork or vfork child (has a fork parent), GDB does not yet
1661 know about this process, and must not know about it until it gets the
1662 corresponding (v)fork event. Exclude this thread from the list. */
1663 if (target_thread_pending_parent (thread
) != nullptr)
1666 write_ptid (ptid_s
, ptid
);
1668 buffer_xml_printf (buffer
, "<thread id=\"%s\"", ptid_s
);
1672 sprintf (core_s
, "%d", core
);
1673 buffer_xml_printf (buffer
, " core=\"%s\"", core_s
);
1677 buffer_xml_printf (buffer
, " name=\"%s\"", name
);
1681 char *handle_s
= (char *) alloca (handle_len
* 2 + 1);
1682 bin2hex (handle
, handle_s
, handle_len
);
1683 buffer_xml_printf (buffer
, " handle=\"%s\"", handle_s
);
1686 buffer_xml_printf (buffer
, "/>\n");
1689 /* Helper for handle_qxfer_threads. Return true on success, false
1693 handle_qxfer_threads_proper (struct buffer
*buffer
)
1695 client_state
&cs
= get_client_state ();
1697 scoped_restore save_current_thread
1698 = make_scoped_restore (¤t_thread
);
1699 scoped_restore save_current_general_thread
1700 = make_scoped_restore (&cs
.general_thread
);
1702 buffer_grow_str (buffer
, "<threads>\n");
1704 process_info
*error_proc
= find_process ([&] (process_info
*process
)
1706 /* The target may need to access memory and registers (e.g. via
1707 libthread_db) to fetch thread properties. Prepare for memory
1708 access here, so that we potentially pause threads just once
1709 for all accesses. Note that even if someday we stop needing
1710 to pause threads to access memory, we will need to be able to
1711 access registers, or other ptrace accesses like
1712 PTRACE_GET_THREAD_AREA. */
1714 /* Need to switch to each process in turn, because
1715 prepare_to_access_memory prepares for an access in the
1716 current process pointed to by general_thread. */
1717 switch_to_process (process
);
1718 cs
.general_thread
= current_thread
->id
;
1720 int res
= prepare_to_access_memory ();
1723 for_each_thread (process
->pid
, [&] (thread_info
*thread
)
1725 handle_qxfer_threads_worker (thread
, buffer
);
1728 done_accessing_memory ();
1735 buffer_grow_str0 (buffer
, "</threads>\n");
1736 return error_proc
== nullptr;
1739 /* Handle qXfer:threads:read. */
1742 handle_qxfer_threads (const char *annex
,
1743 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1744 ULONGEST offset
, LONGEST len
)
1746 static char *result
= 0;
1747 static unsigned int result_length
= 0;
1749 if (writebuf
!= NULL
)
1752 if (annex
[0] != '\0')
1757 struct buffer buffer
;
1758 /* When asked for data at offset 0, generate everything and store into
1759 'result'. Successive reads will be served off 'result'. */
1763 buffer_init (&buffer
);
1765 bool res
= handle_qxfer_threads_proper (&buffer
);
1767 result
= buffer_finish (&buffer
);
1768 result_length
= strlen (result
);
1769 buffer_free (&buffer
);
1775 if (offset
>= result_length
)
1777 /* We're out of data. */
1784 if (len
> result_length
- offset
)
1785 len
= result_length
- offset
;
1787 memcpy (readbuf
, result
+ offset
, len
);
1792 /* Handle qXfer:traceframe-info:read. */
1795 handle_qxfer_traceframe_info (const char *annex
,
1796 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1797 ULONGEST offset
, LONGEST len
)
1799 client_state
&cs
= get_client_state ();
1800 static char *result
= 0;
1801 static unsigned int result_length
= 0;
1803 if (writebuf
!= NULL
)
1806 if (!target_running () || annex
[0] != '\0' || cs
.current_traceframe
== -1)
1811 struct buffer buffer
;
1813 /* When asked for data at offset 0, generate everything and
1814 store into 'result'. Successive reads will be served off
1818 buffer_init (&buffer
);
1820 traceframe_read_info (cs
.current_traceframe
, &buffer
);
1822 result
= buffer_finish (&buffer
);
1823 result_length
= strlen (result
);
1824 buffer_free (&buffer
);
1827 if (offset
>= result_length
)
1829 /* We're out of data. */
1836 if (len
> result_length
- offset
)
1837 len
= result_length
- offset
;
1839 memcpy (readbuf
, result
+ offset
, len
);
1843 /* Handle qXfer:fdpic:read. */
1846 handle_qxfer_fdpic (const char *annex
, gdb_byte
*readbuf
,
1847 const gdb_byte
*writebuf
, ULONGEST offset
, LONGEST len
)
1849 if (!the_target
->supports_read_loadmap ())
1852 if (current_thread
== NULL
)
1855 return the_target
->read_loadmap (annex
, offset
, readbuf
, len
);
1858 /* Handle qXfer:btrace:read. */
1861 handle_qxfer_btrace (const char *annex
,
1862 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1863 ULONGEST offset
, LONGEST len
)
1865 client_state
&cs
= get_client_state ();
1866 static struct buffer cache
;
1867 struct thread_info
*thread
;
1868 enum btrace_read_type type
;
1871 if (writebuf
!= NULL
)
1874 if (cs
.general_thread
== null_ptid
1875 || cs
.general_thread
== minus_one_ptid
)
1877 strcpy (cs
.own_buf
, "E.Must select a single thread.");
1881 thread
= find_thread_ptid (cs
.general_thread
);
1884 strcpy (cs
.own_buf
, "E.No such thread.");
1888 if (thread
->btrace
== NULL
)
1890 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
1894 if (strcmp (annex
, "all") == 0)
1895 type
= BTRACE_READ_ALL
;
1896 else if (strcmp (annex
, "new") == 0)
1897 type
= BTRACE_READ_NEW
;
1898 else if (strcmp (annex
, "delta") == 0)
1899 type
= BTRACE_READ_DELTA
;
1902 strcpy (cs
.own_buf
, "E.Bad annex.");
1908 buffer_free (&cache
);
1912 result
= target_read_btrace (thread
->btrace
, &cache
, type
);
1914 memcpy (cs
.own_buf
, cache
.buffer
, cache
.used_size
);
1916 catch (const gdb_exception_error
&exception
)
1918 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
1925 else if (offset
> cache
.used_size
)
1927 buffer_free (&cache
);
1931 if (len
> cache
.used_size
- offset
)
1932 len
= cache
.used_size
- offset
;
1934 memcpy (readbuf
, cache
.buffer
+ offset
, len
);
1939 /* Handle qXfer:btrace-conf:read. */
1942 handle_qxfer_btrace_conf (const char *annex
,
1943 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1944 ULONGEST offset
, LONGEST len
)
1946 client_state
&cs
= get_client_state ();
1947 static struct buffer cache
;
1948 struct thread_info
*thread
;
1951 if (writebuf
!= NULL
)
1954 if (annex
[0] != '\0')
1957 if (cs
.general_thread
== null_ptid
1958 || cs
.general_thread
== minus_one_ptid
)
1960 strcpy (cs
.own_buf
, "E.Must select a single thread.");
1964 thread
= find_thread_ptid (cs
.general_thread
);
1967 strcpy (cs
.own_buf
, "E.No such thread.");
1971 if (thread
->btrace
== NULL
)
1973 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
1979 buffer_free (&cache
);
1983 result
= target_read_btrace_conf (thread
->btrace
, &cache
);
1985 memcpy (cs
.own_buf
, cache
.buffer
, cache
.used_size
);
1987 catch (const gdb_exception_error
&exception
)
1989 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
1996 else if (offset
> cache
.used_size
)
1998 buffer_free (&cache
);
2002 if (len
> cache
.used_size
- offset
)
2003 len
= cache
.used_size
- offset
;
2005 memcpy (readbuf
, cache
.buffer
+ offset
, len
);
2010 static const struct qxfer qxfer_packets
[] =
2012 { "auxv", handle_qxfer_auxv
},
2013 { "btrace", handle_qxfer_btrace
},
2014 { "btrace-conf", handle_qxfer_btrace_conf
},
2015 { "exec-file", handle_qxfer_exec_file
},
2016 { "fdpic", handle_qxfer_fdpic
},
2017 { "features", handle_qxfer_features
},
2018 { "libraries", handle_qxfer_libraries
},
2019 { "libraries-svr4", handle_qxfer_libraries_svr4
},
2020 { "osdata", handle_qxfer_osdata
},
2021 { "siginfo", handle_qxfer_siginfo
},
2022 { "statictrace", handle_qxfer_statictrace
},
2023 { "threads", handle_qxfer_threads
},
2024 { "traceframe-info", handle_qxfer_traceframe_info
},
2028 handle_qxfer (char *own_buf
, int packet_len
, int *new_packet_len_p
)
2036 if (!startswith (own_buf
, "qXfer:"))
2039 /* Grab the object, r/w and annex. */
2040 if (decode_xfer (own_buf
+ 6, &object
, &rw
, &annex
, &offset
) < 0)
2042 write_enn (own_buf
);
2047 i
< sizeof (qxfer_packets
) / sizeof (qxfer_packets
[0]);
2050 const struct qxfer
*q
= &qxfer_packets
[i
];
2052 if (strcmp (object
, q
->object
) == 0)
2054 if (strcmp (rw
, "read") == 0)
2056 unsigned char *data
;
2061 /* Grab the offset and length. */
2062 if (decode_xfer_read (offset
, &ofs
, &len
) < 0)
2064 write_enn (own_buf
);
2068 /* Read one extra byte, as an indicator of whether there is
2070 if (len
> PBUFSIZ
- 2)
2072 data
= (unsigned char *) malloc (len
+ 1);
2075 write_enn (own_buf
);
2078 n
= (*q
->xfer
) (annex
, data
, NULL
, ofs
, len
+ 1);
2086 /* Preserve error message. */
2089 write_enn (own_buf
);
2091 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, len
, 1);
2093 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, n
, 0);
2098 else if (strcmp (rw
, "write") == 0)
2103 unsigned char *data
;
2105 strcpy (own_buf
, "E00");
2106 data
= (unsigned char *) malloc (packet_len
- (offset
- own_buf
));
2109 write_enn (own_buf
);
2112 if (decode_xfer_write (offset
, packet_len
- (offset
- own_buf
),
2113 &ofs
, &len
, data
) < 0)
2116 write_enn (own_buf
);
2120 n
= (*q
->xfer
) (annex
, NULL
, data
, ofs
, len
);
2128 /* Preserve error message. */
2131 write_enn (own_buf
);
2133 sprintf (own_buf
, "%x", n
);
2146 /* Compute 32 bit CRC from inferior memory.
2148 On success, return 32 bit CRC.
2149 On failure, return (unsigned long long) -1. */
2151 static unsigned long long
2152 crc32 (CORE_ADDR base
, int len
, unsigned int crc
)
2156 unsigned char byte
= 0;
2158 /* Return failure if memory read fails. */
2159 if (read_inferior_memory (base
, &byte
, 1) != 0)
2160 return (unsigned long long) -1;
2162 crc
= xcrc32 (&byte
, 1, crc
);
2165 return (unsigned long long) crc
;
2168 /* Parse the qMemTags packet request into ADDR and LEN. */
2171 parse_fetch_memtags_request (char *request
, CORE_ADDR
*addr
, size_t *len
,
2174 gdb_assert (startswith (request
, "qMemTags:"));
2176 const char *p
= request
+ strlen ("qMemTags:");
2178 /* Read address and length. */
2179 unsigned int length
= 0;
2180 p
= decode_m_packet_params (p
, addr
, &length
, ':');
2183 /* Read the tag type. */
2184 ULONGEST tag_type
= 0;
2185 p
= unpack_varlen_hex (p
, &tag_type
);
2186 *type
= (int) tag_type
;
2189 /* Add supported btrace packets to BUF. */
2192 supported_btrace_packets (char *buf
)
2194 strcat (buf
, ";Qbtrace:bts+");
2195 strcat (buf
, ";Qbtrace-conf:bts:size+");
2196 strcat (buf
, ";Qbtrace:pt+");
2197 strcat (buf
, ";Qbtrace-conf:pt:size+");
2198 strcat (buf
, ";Qbtrace:off+");
2199 strcat (buf
, ";qXfer:btrace:read+");
2200 strcat (buf
, ";qXfer:btrace-conf:read+");
2203 /* Handle all of the extended 'q' packets. */
2206 handle_query (char *own_buf
, int packet_len
, int *new_packet_len_p
)
2208 client_state
&cs
= get_client_state ();
2209 static std::list
<thread_info
*>::const_iterator thread_iter
;
2211 /* Reply the current thread id. */
2212 if (strcmp ("qC", own_buf
) == 0 && !disable_packet_qC
)
2215 require_running_or_return (own_buf
);
2217 if (cs
.general_thread
!= null_ptid
&& cs
.general_thread
!= minus_one_ptid
)
2218 ptid
= cs
.general_thread
;
2221 thread_iter
= all_threads
.begin ();
2222 ptid
= (*thread_iter
)->id
;
2225 sprintf (own_buf
, "QC");
2227 write_ptid (own_buf
, ptid
);
2231 if (strcmp ("qSymbol::", own_buf
) == 0)
2233 struct thread_info
*save_thread
= current_thread
;
2235 /* For qSymbol, GDB only changes the current thread if the
2236 previous current thread was of a different process. So if
2237 the previous thread is gone, we need to pick another one of
2238 the same process. This can happen e.g., if we followed an
2239 exec in a non-leader thread. */
2240 if (current_thread
== NULL
)
2243 = find_any_thread_of_pid (cs
.general_thread
.pid ());
2245 /* Just in case, if we didn't find a thread, then bail out
2246 instead of crashing. */
2247 if (current_thread
== NULL
)
2249 write_enn (own_buf
);
2250 current_thread
= save_thread
;
2255 /* GDB is suggesting new symbols have been loaded. This may
2256 mean a new shared library has been detected as loaded, so
2257 take the opportunity to check if breakpoints we think are
2258 inserted, still are. Note that it isn't guaranteed that
2259 we'll see this when a shared library is loaded, and nor will
2260 we see this for unloads (although breakpoints in unloaded
2261 libraries shouldn't trigger), as GDB may not find symbols for
2262 the library at all. We also re-validate breakpoints when we
2263 see a second GDB breakpoint for the same address, and or when
2264 we access breakpoint shadows. */
2265 validate_breakpoints ();
2267 if (target_supports_tracepoints ())
2268 tracepoint_look_up_symbols ();
2270 if (current_thread
!= NULL
)
2271 the_target
->look_up_symbols ();
2273 current_thread
= save_thread
;
2275 strcpy (own_buf
, "OK");
2279 if (!disable_packet_qfThreadInfo
)
2281 if (strcmp ("qfThreadInfo", own_buf
) == 0)
2283 require_running_or_return (own_buf
);
2284 thread_iter
= all_threads
.begin ();
2287 ptid_t ptid
= (*thread_iter
)->id
;
2288 write_ptid (own_buf
, ptid
);
2293 if (strcmp ("qsThreadInfo", own_buf
) == 0)
2295 require_running_or_return (own_buf
);
2296 if (thread_iter
!= all_threads
.end ())
2299 ptid_t ptid
= (*thread_iter
)->id
;
2300 write_ptid (own_buf
, ptid
);
2306 sprintf (own_buf
, "l");
2312 if (the_target
->supports_read_offsets ()
2313 && strcmp ("qOffsets", own_buf
) == 0)
2315 CORE_ADDR text
, data
;
2317 require_running_or_return (own_buf
);
2318 if (the_target
->read_offsets (&text
, &data
))
2319 sprintf (own_buf
, "Text=%lX;Data=%lX;Bss=%lX",
2320 (long)text
, (long)data
, (long)data
);
2322 write_enn (own_buf
);
2327 /* Protocol features query. */
2328 if (startswith (own_buf
, "qSupported")
2329 && (own_buf
[10] == ':' || own_buf
[10] == '\0'))
2331 char *p
= &own_buf
[10];
2332 int gdb_supports_qRelocInsn
= 0;
2334 /* Process each feature being provided by GDB. The first
2335 feature will follow a ':', and latter features will follow
2339 std::vector
<std::string
> qsupported
;
2340 std::vector
<const char *> unknowns
;
2342 /* Two passes, to avoid nested strtok calls in
2343 target_process_qsupported. */
2345 for (p
= strtok_r (p
+ 1, ";", &saveptr
);
2347 p
= strtok_r (NULL
, ";", &saveptr
))
2348 qsupported
.emplace_back (p
);
2350 for (const std::string
&feature
: qsupported
)
2352 if (feature
== "multiprocess+")
2354 /* GDB supports and wants multi-process support if
2356 if (target_supports_multi_process ())
2357 cs
.multi_process
= 1;
2359 else if (feature
== "qRelocInsn+")
2361 /* GDB supports relocate instruction requests. */
2362 gdb_supports_qRelocInsn
= 1;
2364 else if (feature
== "swbreak+")
2366 /* GDB wants us to report whether a trap is caused
2367 by a software breakpoint and for us to handle PC
2368 adjustment if necessary on this target. */
2369 if (target_supports_stopped_by_sw_breakpoint ())
2370 cs
.swbreak_feature
= 1;
2372 else if (feature
== "hwbreak+")
2374 /* GDB wants us to report whether a trap is caused
2375 by a hardware breakpoint. */
2376 if (target_supports_stopped_by_hw_breakpoint ())
2377 cs
.hwbreak_feature
= 1;
2379 else if (feature
== "fork-events+")
2381 /* GDB supports and wants fork events if possible. */
2382 if (target_supports_fork_events ())
2383 cs
.report_fork_events
= 1;
2385 else if (feature
== "vfork-events+")
2387 /* GDB supports and wants vfork events if possible. */
2388 if (target_supports_vfork_events ())
2389 cs
.report_vfork_events
= 1;
2391 else if (feature
== "exec-events+")
2393 /* GDB supports and wants exec events if possible. */
2394 if (target_supports_exec_events ())
2395 cs
.report_exec_events
= 1;
2397 else if (feature
== "vContSupported+")
2398 cs
.vCont_supported
= 1;
2399 else if (feature
== "QThreadEvents+")
2401 else if (feature
== "no-resumed+")
2403 /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
2405 report_no_resumed
= true;
2407 else if (feature
== "memory-tagging+")
2409 /* GDB supports memory tagging features. */
2410 if (target_supports_memory_tagging ())
2411 cs
.memory_tagging_feature
= true;
2415 /* Move the unknown features all together. */
2416 unknowns
.push_back (feature
.c_str ());
2420 /* Give the target backend a chance to process the unknown
2422 target_process_qsupported (unknowns
);
2426 "PacketSize=%x;QPassSignals+;QProgramSignals+;"
2427 "QStartupWithShell+;QEnvironmentHexEncoded+;"
2428 "QEnvironmentReset+;QEnvironmentUnset+;"
2432 if (target_supports_catch_syscall ())
2433 strcat (own_buf
, ";QCatchSyscalls+");
2435 if (the_target
->supports_qxfer_libraries_svr4 ())
2436 strcat (own_buf
, ";qXfer:libraries-svr4:read+"
2437 ";augmented-libraries-svr4-read+");
2440 /* We do not have any hook to indicate whether the non-SVR4 target
2441 backend supports qXfer:libraries:read, so always report it. */
2442 strcat (own_buf
, ";qXfer:libraries:read+");
2445 if (the_target
->supports_read_auxv ())
2446 strcat (own_buf
, ";qXfer:auxv:read+");
2448 if (the_target
->supports_qxfer_siginfo ())
2449 strcat (own_buf
, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2451 if (the_target
->supports_read_loadmap ())
2452 strcat (own_buf
, ";qXfer:fdpic:read+");
2454 /* We always report qXfer:features:read, as targets may
2455 install XML files on a subsequent call to arch_setup.
2456 If we reported to GDB on startup that we don't support
2457 qXfer:feature:read at all, we will never be re-queried. */
2458 strcat (own_buf
, ";qXfer:features:read+");
2460 if (cs
.transport_is_reliable
)
2461 strcat (own_buf
, ";QStartNoAckMode+");
2463 if (the_target
->supports_qxfer_osdata ())
2464 strcat (own_buf
, ";qXfer:osdata:read+");
2466 if (target_supports_multi_process ())
2467 strcat (own_buf
, ";multiprocess+");
2469 if (target_supports_fork_events ())
2470 strcat (own_buf
, ";fork-events+");
2472 if (target_supports_vfork_events ())
2473 strcat (own_buf
, ";vfork-events+");
2475 if (target_supports_exec_events ())
2476 strcat (own_buf
, ";exec-events+");
2478 if (target_supports_non_stop ())
2479 strcat (own_buf
, ";QNonStop+");
2481 if (target_supports_disable_randomization ())
2482 strcat (own_buf
, ";QDisableRandomization+");
2484 strcat (own_buf
, ";qXfer:threads:read+");
2486 if (target_supports_tracepoints ())
2488 strcat (own_buf
, ";ConditionalTracepoints+");
2489 strcat (own_buf
, ";TraceStateVariables+");
2490 strcat (own_buf
, ";TracepointSource+");
2491 strcat (own_buf
, ";DisconnectedTracing+");
2492 if (gdb_supports_qRelocInsn
&& target_supports_fast_tracepoints ())
2493 strcat (own_buf
, ";FastTracepoints+");
2494 strcat (own_buf
, ";StaticTracepoints+");
2495 strcat (own_buf
, ";InstallInTrace+");
2496 strcat (own_buf
, ";qXfer:statictrace:read+");
2497 strcat (own_buf
, ";qXfer:traceframe-info:read+");
2498 strcat (own_buf
, ";EnableDisableTracepoints+");
2499 strcat (own_buf
, ";QTBuffer:size+");
2500 strcat (own_buf
, ";tracenz+");
2503 if (target_supports_hardware_single_step ()
2504 || target_supports_software_single_step () )
2506 strcat (own_buf
, ";ConditionalBreakpoints+");
2508 strcat (own_buf
, ";BreakpointCommands+");
2510 if (target_supports_agent ())
2511 strcat (own_buf
, ";QAgent+");
2513 supported_btrace_packets (own_buf
);
2515 if (target_supports_stopped_by_sw_breakpoint ())
2516 strcat (own_buf
, ";swbreak+");
2518 if (target_supports_stopped_by_hw_breakpoint ())
2519 strcat (own_buf
, ";hwbreak+");
2521 if (the_target
->supports_pid_to_exec_file ())
2522 strcat (own_buf
, ";qXfer:exec-file:read+");
2524 strcat (own_buf
, ";vContSupported+");
2526 strcat (own_buf
, ";QThreadEvents+");
2528 strcat (own_buf
, ";no-resumed+");
2530 if (target_supports_memory_tagging ())
2531 strcat (own_buf
, ";memory-tagging+");
2533 /* Reinitialize components as needed for the new connection. */
2534 hostio_handle_new_gdb_connection ();
2535 target_handle_new_gdb_connection ();
2540 /* Thread-local storage support. */
2541 if (the_target
->supports_get_tls_address ()
2542 && startswith (own_buf
, "qGetTLSAddr:"))
2544 char *p
= own_buf
+ 12;
2545 CORE_ADDR parts
[2], address
= 0;
2547 ptid_t ptid
= null_ptid
;
2549 require_running_or_return (own_buf
);
2551 for (i
= 0; i
< 3; i
++)
2559 p2
= strchr (p
, ',');
2572 ptid
= read_ptid (p
, NULL
);
2574 decode_address (&parts
[i
- 1], p
, len
);
2578 if (p
!= NULL
|| i
< 3)
2582 struct thread_info
*thread
= find_thread_ptid (ptid
);
2587 err
= the_target
->get_tls_address (thread
, parts
[0], parts
[1],
2593 strcpy (own_buf
, paddress(address
));
2598 write_enn (own_buf
);
2602 /* Otherwise, pretend we do not understand this packet. */
2605 /* Windows OS Thread Information Block address support. */
2606 if (the_target
->supports_get_tib_address ()
2607 && startswith (own_buf
, "qGetTIBAddr:"))
2612 ptid_t ptid
= read_ptid (own_buf
+ 12, &annex
);
2614 n
= the_target
->get_tib_address (ptid
, &tlb
);
2617 strcpy (own_buf
, paddress(tlb
));
2622 write_enn (own_buf
);
2628 /* Handle "monitor" commands. */
2629 if (startswith (own_buf
, "qRcmd,"))
2631 char *mon
= (char *) malloc (PBUFSIZ
);
2632 int len
= strlen (own_buf
+ 6);
2636 write_enn (own_buf
);
2641 || hex2bin (own_buf
+ 6, (gdb_byte
*) mon
, len
/ 2) != len
/ 2)
2643 write_enn (own_buf
);
2647 mon
[len
/ 2] = '\0';
2651 if (the_target
->handle_monitor_command (mon
) == 0)
2652 /* Default processing. */
2653 handle_monitor_command (mon
, own_buf
);
2659 if (startswith (own_buf
, "qSearch:memory:"))
2661 require_running_or_return (own_buf
);
2662 handle_search_memory (own_buf
, packet_len
);
2666 if (strcmp (own_buf
, "qAttached") == 0
2667 || startswith (own_buf
, "qAttached:"))
2669 struct process_info
*process
;
2671 if (own_buf
[sizeof ("qAttached") - 1])
2673 int pid
= strtoul (own_buf
+ sizeof ("qAttached:") - 1, NULL
, 16);
2674 process
= find_process_pid (pid
);
2678 require_running_or_return (own_buf
);
2679 process
= current_process ();
2682 if (process
== NULL
)
2684 write_enn (own_buf
);
2688 strcpy (own_buf
, process
->attached
? "1" : "0");
2692 if (startswith (own_buf
, "qCRC:"))
2694 /* CRC check (compare-section). */
2698 unsigned long long crc
;
2700 require_running_or_return (own_buf
);
2701 comma
= unpack_varlen_hex (own_buf
+ 5, &base
);
2702 if (*comma
++ != ',')
2704 write_enn (own_buf
);
2707 len
= strtoul (comma
, NULL
, 16);
2708 crc
= crc32 (base
, len
, 0xffffffff);
2709 /* Check for memory failure. */
2710 if (crc
== (unsigned long long) -1)
2712 write_enn (own_buf
);
2715 sprintf (own_buf
, "C%lx", (unsigned long) crc
);
2719 if (handle_qxfer (own_buf
, packet_len
, new_packet_len_p
))
2722 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf
))
2725 /* Handle fetch memory tags packets. */
2726 if (startswith (own_buf
, "qMemTags:")
2727 && target_supports_memory_tagging ())
2729 gdb::byte_vector tags
;
2734 require_running_or_return (own_buf
);
2736 parse_fetch_memtags_request (own_buf
, &addr
, &len
, &type
);
2738 bool ret
= the_target
->fetch_memtags (addr
, len
, tags
, type
);
2741 ret
= create_fetch_memtags_reply (own_buf
, tags
);
2744 write_enn (own_buf
);
2746 *new_packet_len_p
= strlen (own_buf
);
2750 /* Otherwise we didn't know what packet it was. Say we didn't
2755 static void gdb_wants_all_threads_stopped (void);
2756 static void resume (struct thread_resume
*actions
, size_t n
);
2758 /* The callback that is passed to visit_actioned_threads. */
2759 typedef int (visit_actioned_threads_callback_ftype
)
2760 (const struct thread_resume
*, struct thread_info
*);
2762 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
2763 true if CALLBACK returns true. Returns false if no matching thread
2764 is found or CALLBACK results false.
2765 Note: This function is itself a callback for find_thread. */
2768 visit_actioned_threads (thread_info
*thread
,
2769 const struct thread_resume
*actions
,
2771 visit_actioned_threads_callback_ftype
*callback
)
2773 for (size_t i
= 0; i
< num_actions
; i
++)
2775 const struct thread_resume
*action
= &actions
[i
];
2777 if (action
->thread
== minus_one_ptid
2778 || action
->thread
== thread
->id
2779 || ((action
->thread
.pid ()
2780 == thread
->id
.pid ())
2781 && action
->thread
.lwp () == -1))
2783 if ((*callback
) (action
, thread
))
2791 /* Callback for visit_actioned_threads. If the thread has a pending
2792 status to report, report it now. */
2795 handle_pending_status (const struct thread_resume
*resumption
,
2796 struct thread_info
*thread
)
2798 client_state
&cs
= get_client_state ();
2799 if (thread
->status_pending_p
)
2801 thread
->status_pending_p
= 0;
2803 cs
.last_status
= thread
->last_status
;
2804 cs
.last_ptid
= thread
->id
;
2805 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, &cs
.last_status
);
2811 /* Parse vCont packets. */
2813 handle_v_cont (char *own_buf
)
2817 struct thread_resume
*resume_info
;
2818 struct thread_resume default_action
{ null_ptid
};
2820 /* Count the number of semicolons in the packet. There should be one
2821 for every action. */
2827 p
= strchr (p
, ';');
2830 resume_info
= (struct thread_resume
*) malloc (n
* sizeof (resume_info
[0]));
2831 if (resume_info
== NULL
)
2839 memset (&resume_info
[i
], 0, sizeof resume_info
[i
]);
2841 if (p
[0] == 's' || p
[0] == 'S')
2842 resume_info
[i
].kind
= resume_step
;
2843 else if (p
[0] == 'r')
2844 resume_info
[i
].kind
= resume_step
;
2845 else if (p
[0] == 'c' || p
[0] == 'C')
2846 resume_info
[i
].kind
= resume_continue
;
2847 else if (p
[0] == 't')
2848 resume_info
[i
].kind
= resume_stop
;
2852 if (p
[0] == 'S' || p
[0] == 'C')
2855 int sig
= strtol (p
+ 1, &q
, 16);
2860 if (!gdb_signal_to_host_p ((enum gdb_signal
) sig
))
2862 resume_info
[i
].sig
= gdb_signal_to_host ((enum gdb_signal
) sig
);
2864 else if (p
[0] == 'r')
2868 p
= unpack_varlen_hex (p
+ 1, &addr
);
2869 resume_info
[i
].step_range_start
= addr
;
2874 p
= unpack_varlen_hex (p
+ 1, &addr
);
2875 resume_info
[i
].step_range_end
= addr
;
2884 resume_info
[i
].thread
= minus_one_ptid
;
2885 default_action
= resume_info
[i
];
2887 /* Note: we don't increment i here, we'll overwrite this entry
2888 the next time through. */
2890 else if (p
[0] == ':')
2893 ptid_t ptid
= read_ptid (p
+ 1, &q
);
2898 if (p
[0] != ';' && p
[0] != 0)
2901 resume_info
[i
].thread
= ptid
;
2908 resume_info
[i
] = default_action
;
2910 resume (resume_info
, n
);
2915 write_enn (own_buf
);
2920 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
2923 resume (struct thread_resume
*actions
, size_t num_actions
)
2925 client_state
&cs
= get_client_state ();
2928 /* Check if among the threads that GDB wants actioned, there's
2929 one with a pending status to report. If so, skip actually
2930 resuming/stopping and report the pending event
2933 thread_info
*thread_with_status
= find_thread ([&] (thread_info
*thread
)
2935 return visit_actioned_threads (thread
, actions
, num_actions
,
2936 handle_pending_status
);
2939 if (thread_with_status
!= NULL
)
2945 the_target
->resume (actions
, num_actions
);
2948 write_ok (cs
.own_buf
);
2951 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
, 0, 1);
2953 if (cs
.last_status
.kind
== TARGET_WAITKIND_NO_RESUMED
2954 && !report_no_resumed
)
2956 /* The client does not support this stop reply. At least
2958 sprintf (cs
.own_buf
, "E.No unwaited-for children left.");
2959 disable_async_io ();
2963 if (cs
.last_status
.kind
!= TARGET_WAITKIND_EXITED
2964 && cs
.last_status
.kind
!= TARGET_WAITKIND_SIGNALLED
2965 && cs
.last_status
.kind
!= TARGET_WAITKIND_NO_RESUMED
)
2966 current_thread
->last_status
= cs
.last_status
;
2968 /* From the client's perspective, all-stop mode always stops all
2969 threads implicitly (and the target backend has already done
2970 so by now). Tag all threads as "want-stopped", so we don't
2971 resume them implicitly without the client telling us to. */
2972 gdb_wants_all_threads_stopped ();
2973 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, &cs
.last_status
);
2974 disable_async_io ();
2976 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
2977 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
2978 target_mourn_inferior (cs
.last_ptid
);
2982 /* Attach to a new program. */
2984 handle_v_attach (char *own_buf
)
2986 client_state
&cs
= get_client_state ();
2989 pid
= strtol (own_buf
+ 8, NULL
, 16);
2990 if (pid
!= 0 && attach_inferior (pid
) == 0)
2992 /* Don't report shared library events after attaching, even if
2993 some libraries are preloaded. GDB will always poll the
2994 library list. Avoids the "stopped by shared library event"
2995 notice on the GDB side. */
2996 current_process ()->dlls_changed
= false;
3000 /* In non-stop, we don't send a resume reply. Stop events
3001 will follow up using the normal notification
3006 prepare_resume_reply (own_buf
, cs
.last_ptid
, &cs
.last_status
);
3009 write_enn (own_buf
);
3012 /* Run a new program. */
3014 handle_v_run (char *own_buf
)
3016 client_state
&cs
= get_client_state ();
3018 std::vector
<char *> new_argv
;
3019 char *new_program_name
= NULL
;
3023 for (p
= own_buf
+ strlen ("vRun;"); p
&& *p
; p
= strchr (p
, ';'))
3029 for (i
= 0, p
= own_buf
+ strlen ("vRun;"); *p
; p
= next_p
, ++i
)
3031 next_p
= strchr (p
, ';');
3033 next_p
= p
+ strlen (p
);
3035 if (i
== 0 && p
== next_p
)
3037 /* No program specified. */
3038 new_program_name
= NULL
;
3040 else if (p
== next_p
)
3042 /* Empty argument. */
3043 new_argv
.push_back (xstrdup (""));
3047 size_t len
= (next_p
- p
) / 2;
3048 /* ARG is the unquoted argument received via the RSP. */
3049 char *arg
= (char *) xmalloc (len
+ 1);
3050 /* FULL_ARGS will contain the quoted version of ARG. */
3051 char *full_arg
= (char *) xmalloc ((len
+ 1) * 2);
3052 /* These are pointers used to navigate the strings above. */
3053 char *tmp_arg
= arg
;
3054 char *tmp_full_arg
= full_arg
;
3057 hex2bin (p
, (gdb_byte
*) arg
, len
);
3060 while (*tmp_arg
!= '\0')
3066 *tmp_full_arg
= '\'';
3072 /* Quote single quote. */
3073 *tmp_full_arg
= '\\';
3081 *tmp_full_arg
= *tmp_arg
;
3087 *tmp_full_arg
++ = '\'';
3089 /* Finish FULL_ARG and push it into the vector containing
3091 *tmp_full_arg
= '\0';
3093 new_program_name
= full_arg
;
3095 new_argv
.push_back (full_arg
);
3102 if (new_program_name
== NULL
)
3104 /* GDB didn't specify a program to run. Use the program from the
3105 last run with the new argument list. */
3106 if (program_path
.get () == NULL
)
3108 write_enn (own_buf
);
3109 free_vector_argv (new_argv
);
3114 program_path
.set (gdb::unique_xmalloc_ptr
<char> (new_program_name
));
3116 /* Free the old argv and install the new one. */
3117 free_vector_argv (program_args
);
3118 program_args
= new_argv
;
3120 target_create_inferior (program_path
.get (), program_args
);
3122 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
3124 prepare_resume_reply (own_buf
, cs
.last_ptid
, &cs
.last_status
);
3126 /* In non-stop, sending a resume reply doesn't set the general
3127 thread, but GDB assumes a vRun sets it (this is so GDB can
3128 query which is the main thread of the new inferior. */
3130 cs
.general_thread
= cs
.last_ptid
;
3133 write_enn (own_buf
);
3138 handle_v_kill (char *own_buf
)
3140 client_state
&cs
= get_client_state ();
3142 char *p
= &own_buf
[6];
3143 if (cs
.multi_process
)
3144 pid
= strtol (p
, NULL
, 16);
3148 process_info
*proc
= find_process_pid (pid
);
3150 if (proc
!= nullptr && kill_inferior (proc
) == 0)
3152 cs
.last_status
.kind
= TARGET_WAITKIND_SIGNALLED
;
3153 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
3154 cs
.last_ptid
= ptid_t (pid
);
3155 discard_queued_stop_replies (cs
.last_ptid
);
3159 write_enn (own_buf
);
3162 /* Handle all of the extended 'v' packets. */
3164 handle_v_requests (char *own_buf
, int packet_len
, int *new_packet_len
)
3166 client_state
&cs
= get_client_state ();
3167 if (!disable_packet_vCont
)
3169 if (strcmp (own_buf
, "vCtrlC") == 0)
3171 the_target
->request_interrupt ();
3176 if (startswith (own_buf
, "vCont;"))
3178 handle_v_cont (own_buf
);
3182 if (startswith (own_buf
, "vCont?"))
3184 strcpy (own_buf
, "vCont;c;C;t");
3186 if (target_supports_hardware_single_step ()
3187 || target_supports_software_single_step ()
3188 || !cs
.vCont_supported
)
3190 /* If target supports single step either by hardware or by
3191 software, add actions s and S to the list of supported
3192 actions. On the other hand, if GDB doesn't request the
3193 supported vCont actions in qSupported packet, add s and
3194 S to the list too. */
3195 own_buf
= own_buf
+ strlen (own_buf
);
3196 strcpy (own_buf
, ";s;S");
3199 if (target_supports_range_stepping ())
3201 own_buf
= own_buf
+ strlen (own_buf
);
3202 strcpy (own_buf
, ";r");
3208 if (startswith (own_buf
, "vFile:")
3209 && handle_vFile (own_buf
, packet_len
, new_packet_len
))
3212 if (startswith (own_buf
, "vAttach;"))
3214 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3216 fprintf (stderr
, "Already debugging a process\n");
3217 write_enn (own_buf
);
3220 handle_v_attach (own_buf
);
3224 if (startswith (own_buf
, "vRun;"))
3226 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3228 fprintf (stderr
, "Already debugging a process\n");
3229 write_enn (own_buf
);
3232 handle_v_run (own_buf
);
3236 if (startswith (own_buf
, "vKill;"))
3238 if (!target_running ())
3240 fprintf (stderr
, "No process to kill\n");
3241 write_enn (own_buf
);
3244 handle_v_kill (own_buf
);
3248 if (handle_notif_ack (own_buf
, packet_len
))
3251 /* Otherwise we didn't know what packet it was. Say we didn't
3257 /* Resume thread and wait for another event. In non-stop mode,
3258 don't really wait here, but return immediatelly to the event
3261 myresume (char *own_buf
, int step
, int sig
)
3263 client_state
&cs
= get_client_state ();
3264 struct thread_resume resume_info
[2];
3266 int valid_cont_thread
;
3268 valid_cont_thread
= (cs
.cont_thread
!= null_ptid
3269 && cs
.cont_thread
!= minus_one_ptid
);
3271 if (step
|| sig
|| valid_cont_thread
)
3273 resume_info
[0].thread
= current_ptid
;
3275 resume_info
[0].kind
= resume_step
;
3277 resume_info
[0].kind
= resume_continue
;
3278 resume_info
[0].sig
= sig
;
3282 if (!valid_cont_thread
)
3284 resume_info
[n
].thread
= minus_one_ptid
;
3285 resume_info
[n
].kind
= resume_continue
;
3286 resume_info
[n
].sig
= 0;
3290 resume (resume_info
, n
);
3293 /* Callback for for_each_thread. Make a new stop reply for each
3297 queue_stop_reply_callback (thread_info
*thread
)
3299 /* For now, assume targets that don't have this callback also don't
3300 manage the thread's last_status field. */
3301 if (!the_target
->supports_thread_stopped ())
3303 struct vstop_notif
*new_notif
= new struct vstop_notif
;
3305 new_notif
->ptid
= thread
->id
;
3306 new_notif
->status
= thread
->last_status
;
3307 /* Pass the last stop reply back to GDB, but don't notify
3309 notif_event_enque (¬if_stop
, new_notif
);
3313 if (target_thread_stopped (thread
))
3317 std::string status_string
3318 = target_waitstatus_to_string (&thread
->last_status
);
3320 debug_printf ("Reporting thread %s as already stopped with %s\n",
3321 target_pid_to_str (thread
->id
),
3322 status_string
.c_str ());
3325 gdb_assert (thread
->last_status
.kind
!= TARGET_WAITKIND_IGNORE
);
3327 /* Pass the last stop reply back to GDB, but don't notify
3329 queue_stop_reply (thread
->id
, &thread
->last_status
);
3334 /* Set this inferior threads's state as "want-stopped". We won't
3335 resume this thread until the client gives us another action for
3339 gdb_wants_thread_stopped (thread_info
*thread
)
3341 thread
->last_resume_kind
= resume_stop
;
3343 if (thread
->last_status
.kind
== TARGET_WAITKIND_IGNORE
)
3345 /* Most threads are stopped implicitly (all-stop); tag that with
3347 thread
->last_status
.kind
= TARGET_WAITKIND_STOPPED
;
3348 thread
->last_status
.value
.sig
= GDB_SIGNAL_0
;
3352 /* Set all threads' states as "want-stopped". */
3355 gdb_wants_all_threads_stopped (void)
3357 for_each_thread (gdb_wants_thread_stopped
);
3360 /* Callback for for_each_thread. If the thread is stopped with an
3361 interesting event, mark it as having a pending event. */
3364 set_pending_status_callback (thread_info
*thread
)
3366 if (thread
->last_status
.kind
!= TARGET_WAITKIND_STOPPED
3367 || (thread
->last_status
.value
.sig
!= GDB_SIGNAL_0
3368 /* A breakpoint, watchpoint or finished step from a previous
3369 GDB run isn't considered interesting for a new GDB run.
3370 If we left those pending, the new GDB could consider them
3371 random SIGTRAPs. This leaves out real async traps. We'd
3372 have to peek into the (target-specific) siginfo to
3373 distinguish those. */
3374 && thread
->last_status
.value
.sig
!= GDB_SIGNAL_TRAP
))
3375 thread
->status_pending_p
= 1;
3378 /* Status handler for the '?' packet. */
3381 handle_status (char *own_buf
)
3383 client_state
&cs
= get_client_state ();
3385 /* GDB is connected, don't forward events to the target anymore. */
3386 for_each_process ([] (process_info
*process
) {
3387 process
->gdb_detached
= 0;
3390 /* In non-stop mode, we must send a stop reply for each stopped
3391 thread. In all-stop mode, just send one for the first stopped
3396 for_each_thread (queue_stop_reply_callback
);
3398 /* The first is sent immediatly. OK is sent if there is no
3399 stopped thread, which is the same handling of the vStopped
3400 packet (by design). */
3401 notif_write_event (¬if_stop
, cs
.own_buf
);
3405 thread_info
*thread
= NULL
;
3407 target_pause_all (false);
3408 target_stabilize_threads ();
3409 gdb_wants_all_threads_stopped ();
3411 /* We can only report one status, but we might be coming out of
3412 non-stop -- if more than one thread is stopped with
3413 interesting events, leave events for the threads we're not
3414 reporting now pending. They'll be reported the next time the
3415 threads are resumed. Start by marking all interesting events
3417 for_each_thread (set_pending_status_callback
);
3419 /* Prefer the last thread that reported an event to GDB (even if
3420 that was a GDB_SIGNAL_TRAP). */
3421 if (cs
.last_status
.kind
!= TARGET_WAITKIND_IGNORE
3422 && cs
.last_status
.kind
!= TARGET_WAITKIND_EXITED
3423 && cs
.last_status
.kind
!= TARGET_WAITKIND_SIGNALLED
)
3424 thread
= find_thread_ptid (cs
.last_ptid
);
3426 /* If the last event thread is not found for some reason, look
3427 for some other thread that might have an event to report. */
3429 thread
= find_thread ([] (thread_info
*thr_arg
)
3431 return thr_arg
->status_pending_p
;
3434 /* If we're still out of luck, simply pick the first thread in
3437 thread
= get_first_thread ();
3441 struct thread_info
*tp
= (struct thread_info
*) thread
;
3443 /* We're reporting this event, so it's no longer
3445 tp
->status_pending_p
= 0;
3447 /* GDB assumes the current thread is the thread we're
3448 reporting the status for. */
3449 cs
.general_thread
= thread
->id
;
3450 set_desired_thread ();
3452 gdb_assert (tp
->last_status
.kind
!= TARGET_WAITKIND_IGNORE
);
3453 prepare_resume_reply (own_buf
, tp
->id
, &tp
->last_status
);
3456 strcpy (own_buf
, "W00");
3461 gdbserver_version (void)
3463 printf ("GNU gdbserver %s%s\n"
3464 "Copyright (C) 2022 Free Software Foundation, Inc.\n"
3465 "gdbserver is free software, covered by the "
3466 "GNU General Public License.\n"
3467 "This gdbserver was configured as \"%s\"\n",
3468 PKGVERSION
, version
, host_name
);
3472 gdbserver_usage (FILE *stream
)
3474 fprintf (stream
, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3475 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3476 "\tgdbserver [OPTIONS] --multi COMM\n"
3478 "COMM may either be a tty device (for serial debugging),\n"
3479 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3480 "stdin/stdout of gdbserver.\n"
3481 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3482 "PID is the process ID to attach to, when --attach is specified.\n"
3484 "Operating modes:\n"
3486 " --attach Attach to running process PID.\n"
3487 " --multi Start server without a specific program, and\n"
3488 " only quit when explicitly commanded.\n"
3489 " --once Exit after the first connection has closed.\n"
3490 " --help Print this message and then exit.\n"
3491 " --version Display version information and exit.\n"
3495 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3496 " --disable-randomization\n"
3497 " Run PROG with address space randomization disabled.\n"
3498 " --no-disable-randomization\n"
3499 " Don't disable address space randomization when\n"
3501 " --startup-with-shell\n"
3502 " Start PROG using a shell. I.e., execs a shell that\n"
3503 " then execs PROG. (default)\n"
3504 " --no-startup-with-shell\n"
3505 " Exec PROG directly instead of using a shell.\n"
3506 " Disables argument globbing and variable substitution\n"
3507 " on UNIX-like systems.\n"
3511 " --debug Enable general debugging output.\n"
3512 " --debug-format=OPT1[,OPT2,...]\n"
3513 " Specify extra content in debugging output.\n"
3518 " --remote-debug Enable remote protocol debugging output.\n"
3519 " --event-loop-debug Enable event loop debugging output.\n"
3520 " --disable-packet=OPT1[,OPT2,...]\n"
3521 " Disable support for RSP packets or features.\n"
3523 " vCont, T, Tthread, qC, qfThreadInfo and \n"
3524 " threads (disable all threading packets).\n"
3526 "For more information, consult the GDB manual (available as on-line \n"
3527 "info or a printed manual).\n");
3528 if (REPORT_BUGS_TO
[0] && stream
== stdout
)
3529 fprintf (stream
, "Report bugs to \"%s\".\n", REPORT_BUGS_TO
);
3533 gdbserver_show_disableable (FILE *stream
)
3535 fprintf (stream
, "Disableable packets:\n"
3536 " vCont \tAll vCont packets\n"
3537 " qC \tQuerying the current thread\n"
3538 " qfThreadInfo\tThread listing\n"
3539 " Tthread \tPassing the thread specifier in the "
3540 "T stop reply packet\n"
3541 " threads \tAll of the above\n"
3542 " T \tAll 'T' packets\n");
3545 /* Start up the event loop. This is the entry point to the event
3551 /* Loop until there is nothing to do. This is the entry point to
3552 the event loop engine. If nothing is ready at this time, wait
3553 for something to happen (via wait_for_event), then process it.
3554 Return when there are no longer event sources to wait for. */
3556 keep_processing_events
= true;
3557 while (keep_processing_events
)
3559 /* Any events already waiting in the queue? */
3560 int res
= gdb_do_one_event ();
3562 /* Was there an error? */
3567 /* We are done with the event loop. There are no more event sources
3568 to listen to. So we exit gdbserver. */
3572 kill_inferior_callback (process_info
*process
)
3574 kill_inferior (process
);
3575 discard_queued_stop_replies (ptid_t (process
->pid
));
3578 /* Call this when exiting gdbserver with possible inferiors that need
3579 to be killed or detached from. */
3582 detach_or_kill_for_exit (void)
3584 /* First print a list of the inferiors we will be killing/detaching.
3585 This is to assist the user, for example, in case the inferior unexpectedly
3586 dies after we exit: did we screw up or did the inferior exit on its own?
3587 Having this info will save some head-scratching. */
3589 if (have_started_inferiors_p ())
3591 fprintf (stderr
, "Killing process(es):");
3593 for_each_process ([] (process_info
*process
) {
3594 if (!process
->attached
)
3595 fprintf (stderr
, " %d", process
->pid
);
3598 fprintf (stderr
, "\n");
3600 if (have_attached_inferiors_p ())
3602 fprintf (stderr
, "Detaching process(es):");
3604 for_each_process ([] (process_info
*process
) {
3605 if (process
->attached
)
3606 fprintf (stderr
, " %d", process
->pid
);
3609 fprintf (stderr
, "\n");
3612 /* Now we can kill or detach the inferiors. */
3613 for_each_process ([] (process_info
*process
) {
3614 int pid
= process
->pid
;
3616 if (process
->attached
)
3617 detach_inferior (process
);
3619 kill_inferior (process
);
3621 discard_queued_stop_replies (ptid_t (pid
));
3625 /* Value that will be passed to exit(3) when gdbserver exits. */
3626 static int exit_code
;
3628 /* Wrapper for detach_or_kill_for_exit that catches and prints
3632 detach_or_kill_for_exit_cleanup ()
3636 detach_or_kill_for_exit ();
3638 catch (const gdb_exception
&exception
)
3641 fprintf (stderr
, "Detach or kill failed: %s\n",
3649 namespace selftests
{
3652 test_memory_tagging_functions (void)
3654 /* Setup testing. */
3655 gdb::char_vector packet
;
3656 gdb::byte_vector tags
, bv
;
3657 std::string expected
;
3658 packet
.resize (32000);
3663 /* Test parsing a qMemTags request. */
3665 /* Valid request, addr, len and type updated. */
3669 strcpy (packet
.data (), "qMemTags:0,0:0");
3670 parse_fetch_memtags_request (packet
.data (), &addr
, &len
, &type
);
3671 SELF_CHECK (addr
== 0 && len
== 0 && type
== 0);
3673 /* Valid request, addr, len and type updated. */
3677 strcpy (packet
.data (), "qMemTags:deadbeef,ff:5");
3678 parse_fetch_memtags_request (packet
.data (), &addr
, &len
, &type
);
3679 SELF_CHECK (addr
== 0xdeadbeef && len
== 255 && type
== 5);
3681 /* Test creating a qMemTags reply. */
3683 /* Non-empty tag data. */
3686 for (int i
= 0; i
< 5; i
++)
3689 expected
= "m0001020304";
3690 SELF_CHECK (create_fetch_memtags_reply (packet
.data (), bv
) == true);
3691 SELF_CHECK (strcmp (packet
.data (), expected
.c_str ()) == 0);
3693 /* Test parsing a QMemTags request. */
3695 /* Valid request and empty tag data: addr, len, type and tags updated. */
3700 strcpy (packet
.data (), "QMemTags:0,0:0:");
3701 SELF_CHECK (parse_store_memtags_request (packet
.data (),
3702 &addr
, &len
, tags
, &type
) == true);
3703 SELF_CHECK (addr
== 0 && len
== 0 && type
== 0 && tags
.size () == 0);
3705 /* Valid request and non-empty tag data: addr, len, type
3706 and tags updated. */
3711 strcpy (packet
.data (),
3712 "QMemTags:deadbeef,ff:5:0001020304");
3713 SELF_CHECK (parse_store_memtags_request (packet
.data (), &addr
, &len
, tags
,
3715 SELF_CHECK (addr
== 0xdeadbeef && len
== 255 && type
== 5
3716 && tags
.size () == 5);
3719 } // namespace selftests
3720 #endif /* GDB_SELF_TEST */
3722 /* Main function. This is called by the real "main" function,
3723 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
3725 static void ATTRIBUTE_NORETURN
3726 captured_main (int argc
, char *argv
[])
3731 const char *port
= NULL
;
3732 char **next_arg
= &argv
[1];
3733 volatile int multi_mode
= 0;
3734 volatile int attach
= 0;
3736 bool selftest
= false;
3738 std::vector
<const char *> selftest_filters
;
3740 selftests::register_test ("remote_memory_tagging",
3741 selftests::test_memory_tagging_functions
);
3744 current_directory
= getcwd (NULL
, 0);
3745 client_state
&cs
= get_client_state ();
3747 if (current_directory
== NULL
)
3749 error (_("Could not find current working directory: %s"),
3750 safe_strerror (errno
));
3753 while (*next_arg
!= NULL
&& **next_arg
== '-')
3755 if (strcmp (*next_arg
, "--version") == 0)
3757 gdbserver_version ();
3760 else if (strcmp (*next_arg
, "--help") == 0)
3762 gdbserver_usage (stdout
);
3765 else if (strcmp (*next_arg
, "--attach") == 0)
3767 else if (strcmp (*next_arg
, "--multi") == 0)
3769 else if (strcmp (*next_arg
, "--wrapper") == 0)
3776 while (*next_arg
!= NULL
&& strcmp (*next_arg
, "--") != 0)
3778 wrapper_argv
+= *next_arg
;
3779 wrapper_argv
+= ' ';
3783 if (!wrapper_argv
.empty ())
3785 /* Erase the last whitespace. */
3786 wrapper_argv
.erase (wrapper_argv
.end () - 1);
3789 if (next_arg
== tmp
|| *next_arg
== NULL
)
3791 gdbserver_usage (stderr
);
3795 /* Consume the "--". */
3798 else if (strcmp (*next_arg
, "--debug") == 0)
3800 else if (startswith (*next_arg
, "--debug-format="))
3802 std::string error_msg
3803 = parse_debug_format_options ((*next_arg
)
3804 + sizeof ("--debug-format=") - 1, 0);
3806 if (!error_msg
.empty ())
3808 fprintf (stderr
, "%s", error_msg
.c_str ());
3812 else if (strcmp (*next_arg
, "--remote-debug") == 0)
3814 else if (strcmp (*next_arg
, "--event-loop-debug") == 0)
3815 debug_event_loop
= debug_event_loop_kind::ALL
;
3816 else if (startswith (*next_arg
, "--debug-file="))
3817 debug_set_output ((*next_arg
) + sizeof ("--debug-file=") -1);
3818 else if (strcmp (*next_arg
, "--disable-packet") == 0)
3820 gdbserver_show_disableable (stdout
);
3823 else if (startswith (*next_arg
, "--disable-packet="))
3825 char *packets
= *next_arg
+= sizeof ("--disable-packet=") - 1;
3827 for (char *tok
= strtok_r (packets
, ",", &saveptr
);
3829 tok
= strtok_r (NULL
, ",", &saveptr
))
3831 if (strcmp ("vCont", tok
) == 0)
3832 disable_packet_vCont
= true;
3833 else if (strcmp ("Tthread", tok
) == 0)
3834 disable_packet_Tthread
= true;
3835 else if (strcmp ("qC", tok
) == 0)
3836 disable_packet_qC
= true;
3837 else if (strcmp ("qfThreadInfo", tok
) == 0)
3838 disable_packet_qfThreadInfo
= true;
3839 else if (strcmp ("T", tok
) == 0)
3840 disable_packet_T
= true;
3841 else if (strcmp ("threads", tok
) == 0)
3843 disable_packet_vCont
= true;
3844 disable_packet_Tthread
= true;
3845 disable_packet_qC
= true;
3846 disable_packet_qfThreadInfo
= true;
3850 fprintf (stderr
, "Don't know how to disable \"%s\".\n\n",
3852 gdbserver_show_disableable (stderr
);
3857 else if (strcmp (*next_arg
, "-") == 0)
3859 /* "-" specifies a stdio connection and is a form of port
3861 port
= STDIO_CONNECTION_NAME
;
3865 else if (strcmp (*next_arg
, "--disable-randomization") == 0)
3866 cs
.disable_randomization
= 1;
3867 else if (strcmp (*next_arg
, "--no-disable-randomization") == 0)
3868 cs
.disable_randomization
= 0;
3869 else if (strcmp (*next_arg
, "--startup-with-shell") == 0)
3870 startup_with_shell
= true;
3871 else if (strcmp (*next_arg
, "--no-startup-with-shell") == 0)
3872 startup_with_shell
= false;
3873 else if (strcmp (*next_arg
, "--once") == 0)
3875 else if (strcmp (*next_arg
, "--selftest") == 0)
3877 else if (startswith (*next_arg
, "--selftest="))
3882 const char *filter
= *next_arg
+ strlen ("--selftest=");
3883 if (*filter
== '\0')
3885 fprintf (stderr
, _("Error: selftest filter is empty.\n"));
3889 selftest_filters
.push_back (filter
);
3894 fprintf (stderr
, "Unknown argument: %s\n", *next_arg
);
3907 if ((port
== NULL
|| (!attach
&& !multi_mode
&& *next_arg
== NULL
))
3910 gdbserver_usage (stderr
);
3914 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
3915 opened by remote_prepare. */
3918 save_original_signals_state (false);
3920 /* We need to know whether the remote connection is stdio before
3921 starting the inferior. Inferiors created in this scenario have
3922 stdin,stdout redirected. So do this here before we call
3925 remote_prepare (port
);
3930 /* --attach used to come after PORT, so allow it there for
3932 if (*next_arg
!= NULL
&& strcmp (*next_arg
, "--attach") == 0)
3939 && (*next_arg
== NULL
3940 || (*next_arg
)[0] == '\0'
3941 || (pid
= strtoul (*next_arg
, &arg_end
, 0)) == 0
3943 || next_arg
[1] != NULL
))
3948 gdbserver_usage (stderr
);
3952 /* Gather information about the environment. */
3953 our_environ
= gdb_environ::from_host_environ ();
3955 initialize_async_io ();
3957 have_job_control ();
3958 if (target_supports_tracepoints ())
3959 initialize_tracepoint ();
3961 mem_buf
= (unsigned char *) xmalloc (PBUFSIZ
);
3966 selftests::run_tests (selftest_filters
);
3968 printf (_("Selftests have been disabled for this build.\n"));
3970 throw_quit ("Quit");
3973 if (pid
== 0 && *next_arg
!= NULL
)
3977 n
= argc
- (next_arg
- argv
);
3978 program_path
.set (make_unique_xstrdup (next_arg
[0]));
3979 for (i
= 1; i
< n
; i
++)
3980 program_args
.push_back (xstrdup (next_arg
[i
]));
3982 /* Wait till we are at first instruction in program. */
3983 target_create_inferior (program_path
.get (), program_args
);
3985 /* We are now (hopefully) stopped at the first instruction of
3986 the target process. This assumes that the target process was
3987 successfully created. */
3991 if (attach_inferior (pid
) == -1)
3992 error ("Attaching not supported on this target");
3994 /* Otherwise succeeded. */
3998 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
3999 cs
.last_status
.value
.integer
= 0;
4000 cs
.last_ptid
= minus_one_ptid
;
4003 SCOPE_EXIT
{ detach_or_kill_for_exit_cleanup (); };
4005 /* Don't report shared library events on the initial connection,
4006 even if some libraries are preloaded. Avoids the "stopped by
4007 shared library event" notice on gdb side. */
4008 if (current_thread
!= nullptr)
4009 current_process ()->dlls_changed
= false;
4011 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
4012 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
4017 if (!was_running
&& !multi_mode
)
4018 error ("No program to debug");
4023 cs
.multi_process
= 0;
4024 cs
.report_fork_events
= 0;
4025 cs
.report_vfork_events
= 0;
4026 cs
.report_exec_events
= 0;
4027 /* Be sure we're out of tfind mode. */
4028 cs
.current_traceframe
= -1;
4029 cs
.cont_thread
= null_ptid
;
4030 cs
.swbreak_feature
= 0;
4031 cs
.hwbreak_feature
= 0;
4032 cs
.vCont_supported
= 0;
4033 cs
.memory_tagging_feature
= false;
4039 /* Wait for events. This will return when all event sources
4040 are removed from the event loop. */
4041 start_event_loop ();
4043 /* If an exit was requested (using the "monitor exit"
4044 command), terminate now. */
4046 throw_quit ("Quit");
4048 /* The only other way to get here is for getpkt to fail:
4050 - If --once was specified, we're done.
4052 - If not in extended-remote mode, and we're no longer
4053 debugging anything, simply exit: GDB has disconnected
4054 after processing the last process exit.
4056 - Otherwise, close the connection and reopen it at the
4058 if (run_once
|| (!extended_protocol
&& !target_running ()))
4059 throw_quit ("Quit");
4062 "Remote side has terminated connection. "
4063 "GDBserver will reopen the connection.\n");
4065 /* Get rid of any pending statuses. An eventual reconnection
4066 (by the same GDB instance or another) will refresh all its
4067 state from scratch. */
4068 discard_queued_stop_replies (minus_one_ptid
);
4069 for_each_thread ([] (thread_info
*thread
)
4071 thread
->status_pending_p
= 0;
4076 if (disconnected_tracing
)
4078 /* Try to enable non-stop/async mode, so we we can
4079 both wait for an async socket accept, and handle
4080 async target events simultaneously. There's also
4081 no point either in having the target always stop
4082 all threads, when we're going to pass signals
4083 down without informing GDB. */
4086 if (the_target
->start_non_stop (true))
4089 /* Detaching implicitly resumes all threads;
4090 simply disconnecting does not. */
4096 "Disconnected tracing disabled; "
4097 "stopping trace run.\n");
4102 catch (const gdb_exception_error
&exception
)
4105 fprintf (stderr
, "gdbserver: %s\n", exception
.what ());
4107 if (response_needed
)
4109 write_enn (cs
.own_buf
);
4110 putpkt (cs
.own_buf
);
4114 throw_quit ("Quit");
4119 /* Main function. */
4122 main (int argc
, char *argv
[])
4127 captured_main (argc
, argv
);
4129 catch (const gdb_exception
&exception
)
4131 if (exception
.reason
== RETURN_ERROR
)
4134 fprintf (stderr
, "%s\n", exception
.what ());
4135 fprintf (stderr
, "Exiting\n");
4142 gdb_assert_not_reached ("captured_main should never return");
4145 /* Process options coming from Z packets for a breakpoint. PACKET is
4146 the packet buffer. *PACKET is updated to point to the first char
4147 after the last processed option. */
4150 process_point_options (struct gdb_breakpoint
*bp
, const char **packet
)
4152 const char *dataptr
= *packet
;
4155 /* Check if data has the correct format. */
4156 if (*dataptr
!= ';')
4163 if (*dataptr
== ';')
4166 if (*dataptr
== 'X')
4168 /* Conditional expression. */
4170 debug_printf ("Found breakpoint condition.\n");
4171 if (!add_breakpoint_condition (bp
, &dataptr
))
4172 dataptr
= strchrnul (dataptr
, ';');
4174 else if (startswith (dataptr
, "cmds:"))
4176 dataptr
+= strlen ("cmds:");
4178 debug_printf ("Found breakpoint commands %s.\n", dataptr
);
4179 persist
= (*dataptr
== '1');
4181 if (add_breakpoint_commands (bp
, &dataptr
, persist
))
4182 dataptr
= strchrnul (dataptr
, ';');
4186 fprintf (stderr
, "Unknown token %c, ignoring.\n",
4188 /* Skip tokens until we find one that we recognize. */
4189 dataptr
= strchrnul (dataptr
, ';');
4195 /* Event loop callback that handles a serial event. The first byte in
4196 the serial buffer gets us here. We expect characters to arrive at
4197 a brisk pace, so we read the rest of the packet with a blocking
4201 process_serial_event (void)
4203 client_state
&cs
= get_client_state ();
4209 int new_packet_len
= -1;
4211 disable_async_io ();
4213 response_needed
= false;
4214 packet_len
= getpkt (cs
.own_buf
);
4215 if (packet_len
<= 0)
4218 /* Force an event loop break. */
4221 response_needed
= true;
4223 char ch
= cs
.own_buf
[0];
4227 handle_query (cs
.own_buf
, packet_len
, &new_packet_len
);
4230 handle_general_set (cs
.own_buf
);
4233 handle_detach (cs
.own_buf
);
4236 extended_protocol
= true;
4237 write_ok (cs
.own_buf
);
4240 handle_status (cs
.own_buf
);
4243 if (cs
.own_buf
[1] == 'c' || cs
.own_buf
[1] == 'g' || cs
.own_buf
[1] == 's')
4245 require_running_or_break (cs
.own_buf
);
4247 ptid_t thread_id
= read_ptid (&cs
.own_buf
[2], NULL
);
4249 if (thread_id
== null_ptid
|| thread_id
== minus_one_ptid
)
4250 thread_id
= null_ptid
;
4251 else if (thread_id
.is_pid ())
4253 /* The ptid represents a pid. */
4254 thread_info
*thread
= find_any_thread_of_pid (thread_id
.pid ());
4258 write_enn (cs
.own_buf
);
4262 thread_id
= thread
->id
;
4266 /* The ptid represents a lwp/tid. */
4267 if (find_thread_ptid (thread_id
) == NULL
)
4269 write_enn (cs
.own_buf
);
4274 if (cs
.own_buf
[1] == 'g')
4276 if (thread_id
== null_ptid
)
4278 /* GDB is telling us to choose any thread. Check if
4279 the currently selected thread is still valid. If
4280 it is not, select the first available. */
4281 thread_info
*thread
= find_thread_ptid (cs
.general_thread
);
4283 thread
= get_first_thread ();
4284 thread_id
= thread
->id
;
4287 cs
.general_thread
= thread_id
;
4288 set_desired_thread ();
4289 gdb_assert (current_thread
!= NULL
);
4291 else if (cs
.own_buf
[1] == 'c')
4292 cs
.cont_thread
= thread_id
;
4294 write_ok (cs
.own_buf
);
4298 /* Silently ignore it so that gdb can extend the protocol
4299 without compatibility headaches. */
4300 cs
.own_buf
[0] = '\0';
4304 require_running_or_break (cs
.own_buf
);
4305 if (cs
.current_traceframe
>= 0)
4307 struct regcache
*regcache
4308 = new_register_cache (current_target_desc ());
4310 if (fetch_traceframe_registers (cs
.current_traceframe
,
4312 registers_to_string (regcache
, cs
.own_buf
);
4314 write_enn (cs
.own_buf
);
4315 free_register_cache (regcache
);
4319 struct regcache
*regcache
;
4321 if (!set_desired_thread ())
4322 write_enn (cs
.own_buf
);
4325 regcache
= get_thread_regcache (current_thread
, 1);
4326 registers_to_string (regcache
, cs
.own_buf
);
4331 require_running_or_break (cs
.own_buf
);
4332 if (cs
.current_traceframe
>= 0)
4333 write_enn (cs
.own_buf
);
4336 struct regcache
*regcache
;
4338 if (!set_desired_thread ())
4339 write_enn (cs
.own_buf
);
4342 regcache
= get_thread_regcache (current_thread
, 1);
4343 registers_from_string (regcache
, &cs
.own_buf
[1]);
4344 write_ok (cs
.own_buf
);
4350 require_running_or_break (cs
.own_buf
);
4351 decode_m_packet (&cs
.own_buf
[1], &mem_addr
, &len
);
4352 int res
= gdb_read_memory (mem_addr
, mem_buf
, len
);
4354 write_enn (cs
.own_buf
);
4356 bin2hex (mem_buf
, cs
.own_buf
, res
);
4360 require_running_or_break (cs
.own_buf
);
4361 decode_M_packet (&cs
.own_buf
[1], &mem_addr
, &len
, &mem_buf
);
4362 if (gdb_write_memory (mem_addr
, mem_buf
, len
) == 0)
4363 write_ok (cs
.own_buf
);
4365 write_enn (cs
.own_buf
);
4368 require_running_or_break (cs
.own_buf
);
4369 if (decode_X_packet (&cs
.own_buf
[1], packet_len
- 1,
4370 &mem_addr
, &len
, &mem_buf
) < 0
4371 || gdb_write_memory (mem_addr
, mem_buf
, len
) != 0)
4372 write_enn (cs
.own_buf
);
4374 write_ok (cs
.own_buf
);
4377 require_running_or_break (cs
.own_buf
);
4378 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4379 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4380 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4383 myresume (cs
.own_buf
, 0, signal
);
4386 require_running_or_break (cs
.own_buf
);
4387 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4388 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4389 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4392 myresume (cs
.own_buf
, 1, signal
);
4395 require_running_or_break (cs
.own_buf
);
4397 myresume (cs
.own_buf
, 0, signal
);
4400 require_running_or_break (cs
.own_buf
);
4402 myresume (cs
.own_buf
, 1, signal
);
4404 case 'Z': /* insert_ ... */
4406 case 'z': /* remove_ ... */
4411 char type
= cs
.own_buf
[1];
4413 const int insert
= ch
== 'Z';
4414 const char *p
= &cs
.own_buf
[3];
4416 p
= unpack_varlen_hex (p
, &addr
);
4417 kind
= strtol (p
+ 1, &dataptr
, 16);
4421 struct gdb_breakpoint
*bp
;
4423 bp
= set_gdb_breakpoint (type
, addr
, kind
, &res
);
4428 /* GDB may have sent us a list of *point parameters to
4429 be evaluated on the target's side. Read such list
4430 here. If we already have a list of parameters, GDB
4431 is telling us to drop that list and use this one
4433 clear_breakpoint_conditions_and_commands (bp
);
4434 const char *options
= dataptr
;
4435 process_point_options (bp
, &options
);
4439 res
= delete_gdb_breakpoint (type
, addr
, kind
);
4442 write_ok (cs
.own_buf
);
4445 cs
.own_buf
[0] = '\0';
4447 write_enn (cs
.own_buf
);
4451 response_needed
= false;
4452 if (!target_running ())
4453 /* The packet we received doesn't make sense - but we can't
4454 reply to it, either. */
4457 fprintf (stderr
, "Killing all inferiors\n");
4459 for_each_process (kill_inferior_callback
);
4461 /* When using the extended protocol, we wait with no program
4462 running. The traditional protocol will exit instead. */
4463 if (extended_protocol
)
4465 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
4466 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
4474 require_running_or_break (cs
.own_buf
);
4476 ptid_t thread_id
= read_ptid (&cs
.own_buf
[1], NULL
);
4477 if (find_thread_ptid (thread_id
) == NULL
)
4479 write_enn (cs
.own_buf
);
4483 if (mythread_alive (thread_id
))
4484 write_ok (cs
.own_buf
);
4486 write_enn (cs
.own_buf
);
4490 response_needed
= false;
4492 /* Restarting the inferior is only supported in the extended
4494 if (extended_protocol
)
4496 if (target_running ())
4497 for_each_process (kill_inferior_callback
);
4499 fprintf (stderr
, "GDBserver restarting\n");
4501 /* Wait till we are at 1st instruction in prog. */
4502 if (program_path
.get () != NULL
)
4504 target_create_inferior (program_path
.get (), program_args
);
4506 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
4508 /* Stopped at the first instruction of the target
4510 cs
.general_thread
= cs
.last_ptid
;
4514 /* Something went wrong. */
4515 cs
.general_thread
= null_ptid
;
4520 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
4521 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
4527 /* It is a request we don't understand. Respond with an
4528 empty packet so that gdb knows that we don't support this
4530 cs
.own_buf
[0] = '\0';
4534 /* Extended (long) request. */
4535 handle_v_requests (cs
.own_buf
, packet_len
, &new_packet_len
);
4539 /* It is a request we don't understand. Respond with an empty
4540 packet so that gdb knows that we don't support this
4542 cs
.own_buf
[0] = '\0';
4546 if (new_packet_len
!= -1)
4547 putpkt_binary (cs
.own_buf
, new_packet_len
);
4549 putpkt (cs
.own_buf
);
4551 response_needed
= false;
4559 /* Event-loop callback for serial events. */
4562 handle_serial_event (int err
, gdb_client_data client_data
)
4565 debug_printf ("handling possible serial event\n");
4567 /* Really handle it. */
4568 if (process_serial_event () < 0)
4570 keep_processing_events
= false;
4574 /* Be sure to not change the selected thread behind GDB's back.
4575 Important in the non-stop mode asynchronous protocol. */
4576 set_desired_thread ();
4579 /* Push a stop notification on the notification queue. */
4582 push_stop_notification (ptid_t ptid
, struct target_waitstatus
*status
)
4584 struct vstop_notif
*vstop_notif
= new struct vstop_notif
;
4586 vstop_notif
->status
= *status
;
4587 vstop_notif
->ptid
= ptid
;
4588 /* Push Stop notification. */
4589 notif_push (¬if_stop
, vstop_notif
);
4592 /* Event-loop callback for target events. */
4595 handle_target_event (int err
, gdb_client_data client_data
)
4597 client_state
&cs
= get_client_state ();
4599 debug_printf ("handling possible target event\n");
4601 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
,
4604 if (cs
.last_status
.kind
== TARGET_WAITKIND_NO_RESUMED
)
4606 if (gdb_connected () && report_no_resumed
)
4607 push_stop_notification (null_ptid
, &cs
.last_status
);
4609 else if (cs
.last_status
.kind
!= TARGET_WAITKIND_IGNORE
)
4611 int pid
= cs
.last_ptid
.pid ();
4612 struct process_info
*process
= find_process_pid (pid
);
4613 int forward_event
= !gdb_connected () || process
->gdb_detached
;
4615 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
4616 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
4618 mark_breakpoints_out (process
);
4619 target_mourn_inferior (cs
.last_ptid
);
4621 else if (cs
.last_status
.kind
== TARGET_WAITKIND_THREAD_EXITED
)
4625 /* We're reporting this thread as stopped. Update its
4626 "want-stopped" state to what the client wants, until it
4627 gets a new resume action. */
4628 current_thread
->last_resume_kind
= resume_stop
;
4629 current_thread
->last_status
= cs
.last_status
;
4634 if (!target_running ())
4636 /* The last process exited. We're done. */
4640 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
4641 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
4642 || cs
.last_status
.kind
== TARGET_WAITKIND_THREAD_EXITED
)
4646 /* A thread stopped with a signal, but gdb isn't
4647 connected to handle it. Pass it down to the
4648 inferior, as if it wasn't being traced. */
4649 enum gdb_signal signal
;
4652 debug_printf ("GDB not connected; forwarding event %d for"
4654 (int) cs
.last_status
.kind
,
4655 target_pid_to_str (cs
.last_ptid
));
4657 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
4658 signal
= cs
.last_status
.value
.sig
;
4660 signal
= GDB_SIGNAL_0
;
4661 target_continue (cs
.last_ptid
, signal
);
4665 push_stop_notification (cs
.last_ptid
, &cs
.last_status
);
4668 /* Be sure to not change the selected thread behind GDB's back.
4669 Important in the non-stop mode asynchronous protocol. */
4670 set_desired_thread ();
4673 /* See gdbsupport/event-loop.h. */
4676 invoke_async_signal_handlers ()
4681 /* See gdbsupport/event-loop.h. */
4684 check_async_event_handlers ()
4689 /* See gdbsupport/errors.h */
4698 /* See gdbsupport/gdb_select.h. */
4701 gdb_select (int n
, fd_set
*readfds
, fd_set
*writefds
,
4702 fd_set
*exceptfds
, struct timeval
*timeout
)
4704 return select (n
, readfds
, writefds
, exceptfds
, timeout
);
4715 } // namespace selftests
4716 #endif /* GDB_SELF_TEST */