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
, const 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
.child_ptid ().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
.sig () == GDB_SIGNAL_STOP
)
332 cs
.last_status
.set_stopped (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
;
739 remote_debug_printf ("[QEnvironmentHexEncoded received '%s']", p
);
740 remote_debug_printf ("[Environment variable to be set: '%s']",
743 size_t pos
= final_var
.find ('=');
744 if (pos
== std::string::npos
)
746 warning (_("Unexpected format for environment variable: '%s'"),
752 var_name
= final_var
.substr (0, pos
);
753 var_value
= final_var
.substr (pos
+ 1, std::string::npos
);
755 our_environ
.set (var_name
.c_str (), var_value
.c_str ());
761 if (startswith (own_buf
, "QEnvironmentUnset:"))
763 const char *p
= own_buf
+ sizeof ("QEnvironmentUnset:") - 1;
764 std::string varname
= hex2str (p
);
766 remote_debug_printf ("[QEnvironmentUnset received '%s']", p
);
767 remote_debug_printf ("[Environment variable to be unset: '%s']",
770 our_environ
.unset (varname
.c_str ());
776 if (strcmp (own_buf
, "QStartNoAckMode") == 0)
778 remote_debug_printf ("[noack mode enabled]");
785 if (startswith (own_buf
, "QNonStop:"))
787 char *mode
= own_buf
+ 9;
791 if (strcmp (mode
, "0") == 0)
793 else if (strcmp (mode
, "1") == 0)
797 /* We don't know what this mode is, so complain to
799 fprintf (stderr
, "Unknown non-stop mode requested: %s\n",
805 req_str
= req
? "non-stop" : "all-stop";
806 if (the_target
->start_non_stop (req
== 1) != 0)
808 fprintf (stderr
, "Setting %s mode failed\n", req_str
);
813 non_stop
= (req
!= 0);
815 remote_debug_printf ("[%s mode enabled]", req_str
);
821 if (startswith (own_buf
, "QDisableRandomization:"))
823 char *packet
= own_buf
+ strlen ("QDisableRandomization:");
826 unpack_varlen_hex (packet
, &setting
);
827 cs
.disable_randomization
= setting
;
829 remote_debug_printf (cs
.disable_randomization
830 ? "[address space randomization disabled]"
831 : "[address space randomization enabled]");
837 if (target_supports_tracepoints ()
838 && handle_tracepoint_general_set (own_buf
))
841 if (startswith (own_buf
, "QAgent:"))
843 char *mode
= own_buf
+ strlen ("QAgent:");
846 if (strcmp (mode
, "0") == 0)
848 else if (strcmp (mode
, "1") == 0)
852 /* We don't know what this value is, so complain to GDB. */
853 sprintf (own_buf
, "E.Unknown QAgent value");
857 /* Update the flag. */
859 remote_debug_printf ("[%s agent]", req
? "Enable" : "Disable");
864 if (handle_btrace_general_set (own_buf
))
867 if (handle_btrace_conf_general_set (own_buf
))
870 if (startswith (own_buf
, "QThreadEvents:"))
872 char *mode
= own_buf
+ strlen ("QThreadEvents:");
873 enum tribool req
= TRIBOOL_UNKNOWN
;
875 if (strcmp (mode
, "0") == 0)
877 else if (strcmp (mode
, "1") == 0)
881 /* We don't know what this mode is, so complain to GDB. */
883 = string_printf ("E.Unknown thread-events mode requested: %s\n",
885 strcpy (own_buf
, err
.c_str ());
889 cs
.report_thread_events
= (req
== TRIBOOL_TRUE
);
891 remote_debug_printf ("[thread events are now %s]\n",
892 cs
.report_thread_events
? "enabled" : "disabled");
898 if (startswith (own_buf
, "QStartupWithShell:"))
900 const char *value
= own_buf
+ strlen ("QStartupWithShell:");
902 if (strcmp (value
, "1") == 0)
903 startup_with_shell
= true;
904 else if (strcmp (value
, "0") == 0)
905 startup_with_shell
= false;
909 fprintf (stderr
, "Unknown value to startup-with-shell: %s\n",
915 remote_debug_printf ("[Inferior will %s started with shell]",
916 startup_with_shell
? "be" : "not be");
922 if (startswith (own_buf
, "QSetWorkingDir:"))
924 const char *p
= own_buf
+ strlen ("QSetWorkingDir:");
928 std::string path
= hex2str (p
);
930 remote_debug_printf ("[Set the inferior's current directory to %s]",
933 set_inferior_cwd (std::move (path
));
937 /* An empty argument means that we should clear out any
938 previously set cwd for the inferior. */
939 set_inferior_cwd ("");
941 remote_debug_printf ("[Unset the inferior's current directory; will "
942 "use gdbserver's cwd]");
950 /* Handle store memory tags packets. */
951 if (startswith (own_buf
, "QMemTags:")
952 && target_supports_memory_tagging ())
954 gdb::byte_vector tags
;
959 require_running_or_return (own_buf
);
961 bool ret
= parse_store_memtags_request (own_buf
, &addr
, &len
, tags
,
965 ret
= the_target
->store_memtags (addr
, len
, tags
, type
);
975 /* Otherwise we didn't know what packet it was. Say we didn't
981 get_features_xml (const char *annex
)
983 const struct target_desc
*desc
= current_target_desc ();
985 /* `desc->xmltarget' defines what to return when looking for the
986 "target.xml" file. Its contents can either be verbatim XML code
987 (prefixed with a '@') or else the name of the actual XML file to
988 be used in place of "target.xml".
990 This variable is set up from the auto-generated
991 init_registers_... routine for the current target. */
993 if (strcmp (annex
, "target.xml") == 0)
995 const char *ret
= tdesc_get_features_xml (desc
);
1007 /* Look for the annex. */
1008 for (i
= 0; xml_builtin
[i
][0] != NULL
; i
++)
1009 if (strcmp (annex
, xml_builtin
[i
][0]) == 0)
1012 if (xml_builtin
[i
][0] != NULL
)
1013 return xml_builtin
[i
][1];
1021 monitor_show_help (void)
1023 monitor_output ("The following monitor commands are supported:\n");
1024 monitor_output (" set debug <0|1>\n");
1025 monitor_output (" Enable general debugging messages\n");
1026 monitor_output (" set debug-hw-points <0|1>\n");
1027 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
1028 monitor_output (" set remote-debug <0|1>\n");
1029 monitor_output (" Enable remote protocol debugging messages\n");
1030 monitor_output (" set event-loop-debug <0|1>\n");
1031 monitor_output (" Enable event loop debugging messages\n");
1032 monitor_output (" set debug-format option1[,option2,...]\n");
1033 monitor_output (" Add additional information to debugging messages\n");
1034 monitor_output (" Options: all, none");
1035 monitor_output (", timestamp");
1036 monitor_output ("\n");
1037 monitor_output (" exit\n");
1038 monitor_output (" Quit GDBserver\n");
1041 /* Read trace frame or inferior memory. Returns the number of bytes
1042 actually read, zero when no further transfer is possible, and -1 on
1043 error. Return of a positive value smaller than LEN does not
1044 indicate there's no more to be read, only the end of the transfer.
1045 E.g., when GDB reads memory from a traceframe, a first request may
1046 be served from a memory block that does not cover the whole request
1047 length. A following request gets the rest served from either
1048 another block (of the same traceframe) or from the read-only
1052 gdb_read_memory (CORE_ADDR memaddr
, unsigned char *myaddr
, int len
)
1054 client_state
&cs
= get_client_state ();
1057 if (cs
.current_traceframe
>= 0)
1060 ULONGEST length
= len
;
1062 if (traceframe_read_mem (cs
.current_traceframe
,
1063 memaddr
, myaddr
, len
, &nbytes
))
1065 /* Data read from trace buffer, we're done. */
1068 if (!in_readonly_region (memaddr
, length
))
1070 /* Otherwise we have a valid readonly case, fall through. */
1071 /* (assume no half-trace half-real blocks for now) */
1074 res
= prepare_to_access_memory ();
1077 if (set_desired_thread ())
1078 res
= read_inferior_memory (memaddr
, myaddr
, len
);
1081 done_accessing_memory ();
1083 return res
== 0 ? len
: -1;
1089 /* Write trace frame or inferior memory. Actually, writing to trace
1090 frames is forbidden. */
1093 gdb_write_memory (CORE_ADDR memaddr
, const unsigned char *myaddr
, int len
)
1095 client_state
&cs
= get_client_state ();
1096 if (cs
.current_traceframe
>= 0)
1102 ret
= prepare_to_access_memory ();
1105 if (set_desired_thread ())
1106 ret
= target_write_memory (memaddr
, myaddr
, len
);
1109 done_accessing_memory ();
1115 /* Handle qSearch:memory packets. */
1118 handle_search_memory (char *own_buf
, int packet_len
)
1120 CORE_ADDR start_addr
;
1121 CORE_ADDR search_space_len
;
1123 unsigned int pattern_len
;
1125 CORE_ADDR found_addr
;
1126 int cmd_name_len
= sizeof ("qSearch:memory:") - 1;
1128 pattern
= (gdb_byte
*) malloc (packet_len
);
1129 if (pattern
== NULL
)
1130 error ("Unable to allocate memory to perform the search");
1132 if (decode_search_memory_packet (own_buf
+ cmd_name_len
,
1133 packet_len
- cmd_name_len
,
1134 &start_addr
, &search_space_len
,
1135 pattern
, &pattern_len
) < 0)
1138 error ("Error in parsing qSearch:memory packet");
1141 auto read_memory
= [] (CORE_ADDR addr
, gdb_byte
*result
, size_t len
)
1143 return gdb_read_memory (addr
, result
, len
) == len
;
1146 found
= simple_search_memory (read_memory
, start_addr
, search_space_len
,
1147 pattern
, pattern_len
, &found_addr
);
1150 sprintf (own_buf
, "1,%lx", (long) found_addr
);
1151 else if (found
== 0)
1152 strcpy (own_buf
, "0");
1154 strcpy (own_buf
, "E00");
1159 /* Handle the "D" packet. */
1162 handle_detach (char *own_buf
)
1164 client_state
&cs
= get_client_state ();
1166 process_info
*process
;
1168 if (cs
.multi_process
)
1171 int pid
= strtol (&own_buf
[2], NULL
, 16);
1173 process
= find_process_pid (pid
);
1177 process
= (current_thread
!= nullptr
1178 ? get_thread_process (current_thread
)
1182 if (process
== NULL
)
1184 write_enn (own_buf
);
1188 if ((tracing
&& disconnected_tracing
) || any_persistent_commands (process
))
1190 if (tracing
&& disconnected_tracing
)
1192 "Disconnected tracing in effect, "
1193 "leaving gdbserver attached to the process\n");
1195 if (any_persistent_commands (process
))
1197 "Persistent commands are present, "
1198 "leaving gdbserver attached to the process\n");
1200 /* Make sure we're in non-stop/async mode, so we we can both
1201 wait for an async socket accept, and handle async target
1202 events simultaneously. There's also no point either in
1203 having the target stop all threads, when we're going to
1204 pass signals down without informing GDB. */
1207 threads_debug_printf ("Forcing non-stop mode");
1210 the_target
->start_non_stop (true);
1213 process
->gdb_detached
= 1;
1215 /* Detaching implicitly resumes all threads. */
1216 target_continue_no_signal (minus_one_ptid
);
1222 fprintf (stderr
, "Detaching from process %d\n", process
->pid
);
1225 /* We'll need this after PROCESS has been destroyed. */
1226 int pid
= process
->pid
;
1228 /* If this process has an unreported fork child, that child is not known to
1229 GDB, so GDB won't take care of detaching it. We must do it here.
1231 Here, we specifically don't want to use "safe iteration", as detaching
1232 another process might delete the next thread in the iteration, which is
1233 the one saved by the safe iterator. We will never delete the currently
1234 iterated on thread, so standard iteration should be safe. */
1235 for (thread_info
*thread
: all_threads
)
1237 /* Only threads that are of the process we are detaching. */
1238 if (thread
->id
.pid () != pid
)
1241 /* Only threads that have a pending fork event. */
1242 thread_info
*child
= target_thread_pending_child (thread
);
1243 if (child
== nullptr)
1246 process_info
*fork_child_process
= get_thread_process (child
);
1247 gdb_assert (fork_child_process
!= nullptr);
1249 int fork_child_pid
= fork_child_process
->pid
;
1251 if (detach_inferior (fork_child_process
) != 0)
1252 warning (_("Failed to detach fork child %s, child of %s"),
1253 target_pid_to_str (ptid_t (fork_child_pid
)).c_str (),
1254 target_pid_to_str (thread
->id
).c_str ());
1257 if (detach_inferior (process
) != 0)
1258 write_enn (own_buf
);
1261 discard_queued_stop_replies (ptid_t (pid
));
1264 if (extended_protocol
|| target_running ())
1266 /* There is still at least one inferior remaining or
1267 we are in extended mode, so don't terminate gdbserver,
1268 and instead treat this like a normal program exit. */
1269 cs
.last_status
.set_exited (0);
1270 cs
.last_ptid
= ptid_t (pid
);
1272 switch_to_thread (nullptr);
1279 /* If we are attached, then we can exit. Otherwise, we
1280 need to hang around doing nothing, until the child is
1282 join_inferior (pid
);
1288 /* Parse options to --debug-format= and "monitor set debug-format".
1289 ARG is the text after "--debug-format=" or "monitor set debug-format".
1290 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1291 This triggers calls to monitor_output.
1292 The result is an empty string if all options were parsed ok, otherwise an
1293 error message which the caller must free.
1295 N.B. These commands affect all debug format settings, they are not
1296 cumulative. If a format is not specified, it is turned off.
1297 However, we don't go to extra trouble with things like
1298 "monitor set debug-format all,none,timestamp".
1299 Instead we just parse them one at a time, in order.
1301 The syntax for "monitor set debug" we support here is not identical
1302 to gdb's "set debug foo on|off" because we also use this function to
1303 parse "--debug-format=foo,bar". */
1306 parse_debug_format_options (const char *arg
, int is_monitor
)
1308 /* First turn all debug format options off. */
1309 debug_timestamp
= 0;
1311 /* First remove leading spaces, for "monitor set debug-format". */
1312 while (isspace (*arg
))
1315 std::vector
<gdb::unique_xmalloc_ptr
<char>> options
1316 = delim_string_to_char_ptr_vec (arg
, ',');
1318 for (const gdb::unique_xmalloc_ptr
<char> &option
: options
)
1320 if (strcmp (option
.get (), "all") == 0)
1322 debug_timestamp
= 1;
1324 monitor_output ("All extra debug format options enabled.\n");
1326 else if (strcmp (option
.get (), "none") == 0)
1328 debug_timestamp
= 0;
1330 monitor_output ("All extra debug format options disabled.\n");
1332 else if (strcmp (option
.get (), "timestamp") == 0)
1334 debug_timestamp
= 1;
1336 monitor_output ("Timestamps will be added to debug output.\n");
1338 else if (*option
== '\0')
1340 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1344 return string_printf ("Unknown debug-format argument: \"%s\"\n",
1348 return std::string ();
1351 /* Handle monitor commands not handled by target-specific handlers. */
1354 handle_monitor_command (char *mon
, char *own_buf
)
1356 if (strcmp (mon
, "set debug 1") == 0)
1358 debug_threads
= true;
1359 monitor_output ("Debug output enabled.\n");
1361 else if (strcmp (mon
, "set debug 0") == 0)
1363 debug_threads
= false;
1364 monitor_output ("Debug output disabled.\n");
1366 else if (strcmp (mon
, "set debug-hw-points 1") == 0)
1368 show_debug_regs
= 1;
1369 monitor_output ("H/W point debugging output enabled.\n");
1371 else if (strcmp (mon
, "set debug-hw-points 0") == 0)
1373 show_debug_regs
= 0;
1374 monitor_output ("H/W point debugging output disabled.\n");
1376 else if (strcmp (mon
, "set remote-debug 1") == 0)
1378 remote_debug
= true;
1379 monitor_output ("Protocol debug output enabled.\n");
1381 else if (strcmp (mon
, "set remote-debug 0") == 0)
1383 remote_debug
= false;
1384 monitor_output ("Protocol debug output disabled.\n");
1386 else if (strcmp (mon
, "set event-loop-debug 1") == 0)
1388 debug_event_loop
= debug_event_loop_kind::ALL
;
1389 monitor_output ("Event loop debug output enabled.\n");
1391 else if (strcmp (mon
, "set event-loop-debug 0") == 0)
1393 debug_event_loop
= debug_event_loop_kind::OFF
;
1394 monitor_output ("Event loop debug output disabled.\n");
1396 else if (startswith (mon
, "set debug-format "))
1398 std::string error_msg
1399 = parse_debug_format_options (mon
+ sizeof ("set debug-format ") - 1,
1402 if (!error_msg
.empty ())
1404 monitor_output (error_msg
.c_str ());
1405 monitor_show_help ();
1406 write_enn (own_buf
);
1409 else if (strcmp (mon
, "set debug-file") == 0)
1410 debug_set_output (nullptr);
1411 else if (startswith (mon
, "set debug-file "))
1412 debug_set_output (mon
+ sizeof ("set debug-file ") - 1);
1413 else if (strcmp (mon
, "help") == 0)
1414 monitor_show_help ();
1415 else if (strcmp (mon
, "exit") == 0)
1416 exit_requested
= true;
1419 monitor_output ("Unknown monitor command.\n\n");
1420 monitor_show_help ();
1421 write_enn (own_buf
);
1425 /* Associates a callback with each supported qXfer'able object. */
1429 /* The object this handler handles. */
1432 /* Request that the target transfer up to LEN 8-bit bytes of the
1433 target's OBJECT. The OFFSET, for a seekable object, specifies
1434 the starting point. The ANNEX can be used to provide additional
1435 data-specific information to the target.
1437 Return the number of bytes actually transfered, zero when no
1438 further transfer is possible, -1 on error, -2 when the transfer
1439 is not supported, and -3 on a verbose error message that should
1440 be preserved. Return of a positive value smaller than LEN does
1441 not indicate the end of the object, only the end of the transfer.
1443 One, and only one, of readbuf or writebuf must be non-NULL. */
1444 int (*xfer
) (const char *annex
,
1445 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1446 ULONGEST offset
, LONGEST len
);
1449 /* Handle qXfer:auxv:read. */
1452 handle_qxfer_auxv (const char *annex
,
1453 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1454 ULONGEST offset
, LONGEST len
)
1456 if (!the_target
->supports_read_auxv () || writebuf
!= NULL
)
1459 if (annex
[0] != '\0' || current_thread
== NULL
)
1462 return the_target
->read_auxv (offset
, readbuf
, len
);
1465 /* Handle qXfer:exec-file:read. */
1468 handle_qxfer_exec_file (const char *annex
,
1469 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1470 ULONGEST offset
, LONGEST len
)
1475 if (!the_target
->supports_pid_to_exec_file () || writebuf
!= NULL
)
1478 if (annex
[0] == '\0')
1480 if (current_thread
== NULL
)
1483 pid
= pid_of (current_thread
);
1487 annex
= unpack_varlen_hex (annex
, &pid
);
1488 if (annex
[0] != '\0')
1495 const char *file
= the_target
->pid_to_exec_file (pid
);
1499 total_len
= strlen (file
);
1501 if (offset
> total_len
)
1504 if (offset
+ len
> total_len
)
1505 len
= total_len
- offset
;
1507 memcpy (readbuf
, file
+ offset
, len
);
1511 /* Handle qXfer:features:read. */
1514 handle_qxfer_features (const char *annex
,
1515 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1516 ULONGEST offset
, LONGEST len
)
1518 const char *document
;
1521 if (writebuf
!= NULL
)
1524 if (!target_running ())
1527 /* Grab the correct annex. */
1528 document
= get_features_xml (annex
);
1529 if (document
== NULL
)
1532 total_len
= strlen (document
);
1534 if (offset
> total_len
)
1537 if (offset
+ len
> total_len
)
1538 len
= total_len
- offset
;
1540 memcpy (readbuf
, document
+ offset
, len
);
1544 /* Handle qXfer:libraries:read. */
1547 handle_qxfer_libraries (const char *annex
,
1548 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1549 ULONGEST offset
, LONGEST len
)
1551 if (writebuf
!= NULL
)
1554 if (annex
[0] != '\0' || current_thread
== NULL
)
1557 std::string document
= "<library-list version=\"1.0\">\n";
1559 process_info
*proc
= current_process ();
1560 for (const dll_info
&dll
: proc
->all_dlls
)
1561 document
+= string_printf
1562 (" <library name=\"%s\"><segment address=\"0x%s\"/></library>\n",
1563 dll
.name
.c_str (), paddress (dll
.base_addr
));
1565 document
+= "</library-list>\n";
1567 if (offset
> document
.length ())
1570 if (offset
+ len
> document
.length ())
1571 len
= document
.length () - offset
;
1573 memcpy (readbuf
, &document
[offset
], len
);
1578 /* Handle qXfer:libraries-svr4:read. */
1581 handle_qxfer_libraries_svr4 (const char *annex
,
1582 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1583 ULONGEST offset
, LONGEST len
)
1585 if (writebuf
!= NULL
)
1588 if (current_thread
== NULL
1589 || !the_target
->supports_qxfer_libraries_svr4 ())
1592 return the_target
->qxfer_libraries_svr4 (annex
, readbuf
, writebuf
,
1596 /* Handle qXfer:osadata:read. */
1599 handle_qxfer_osdata (const char *annex
,
1600 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1601 ULONGEST offset
, LONGEST len
)
1603 if (!the_target
->supports_qxfer_osdata () || writebuf
!= NULL
)
1606 return the_target
->qxfer_osdata (annex
, readbuf
, NULL
, offset
, len
);
1609 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1612 handle_qxfer_siginfo (const char *annex
,
1613 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1614 ULONGEST offset
, LONGEST len
)
1616 if (!the_target
->supports_qxfer_siginfo ())
1619 if (annex
[0] != '\0' || current_thread
== NULL
)
1622 return the_target
->qxfer_siginfo (annex
, readbuf
, writebuf
, offset
, len
);
1625 /* Handle qXfer:statictrace:read. */
1628 handle_qxfer_statictrace (const char *annex
,
1629 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1630 ULONGEST offset
, LONGEST len
)
1632 client_state
&cs
= get_client_state ();
1635 if (writebuf
!= NULL
)
1638 if (annex
[0] != '\0' || current_thread
== NULL
1639 || cs
.current_traceframe
== -1)
1642 if (traceframe_read_sdata (cs
.current_traceframe
, offset
,
1643 readbuf
, len
, &nbytes
))
1648 /* Helper for handle_qxfer_threads_proper.
1649 Emit the XML to describe the thread of INF. */
1652 handle_qxfer_threads_worker (thread_info
*thread
, struct buffer
*buffer
)
1654 ptid_t ptid
= ptid_of (thread
);
1656 int core
= target_core_of_thread (ptid
);
1658 const char *name
= target_thread_name (ptid
);
1661 bool handle_status
= target_thread_handle (ptid
, &handle
, &handle_len
);
1663 /* If this is a fork or vfork child (has a fork parent), GDB does not yet
1664 know about this process, and must not know about it until it gets the
1665 corresponding (v)fork event. Exclude this thread from the list. */
1666 if (target_thread_pending_parent (thread
) != nullptr)
1669 write_ptid (ptid_s
, ptid
);
1671 buffer_xml_printf (buffer
, "<thread id=\"%s\"", ptid_s
);
1675 sprintf (core_s
, "%d", core
);
1676 buffer_xml_printf (buffer
, " core=\"%s\"", core_s
);
1680 buffer_xml_printf (buffer
, " name=\"%s\"", name
);
1684 char *handle_s
= (char *) alloca (handle_len
* 2 + 1);
1685 bin2hex (handle
, handle_s
, handle_len
);
1686 buffer_xml_printf (buffer
, " handle=\"%s\"", handle_s
);
1689 buffer_xml_printf (buffer
, "/>\n");
1692 /* Helper for handle_qxfer_threads. Return true on success, false
1696 handle_qxfer_threads_proper (struct buffer
*buffer
)
1698 client_state
&cs
= get_client_state ();
1700 scoped_restore_current_thread restore_thread
;
1701 scoped_restore save_current_general_thread
1702 = make_scoped_restore (&cs
.general_thread
);
1704 buffer_grow_str (buffer
, "<threads>\n");
1706 process_info
*error_proc
= find_process ([&] (process_info
*process
)
1708 /* The target may need to access memory and registers (e.g. via
1709 libthread_db) to fetch thread properties. Prepare for memory
1710 access here, so that we potentially pause threads just once
1711 for all accesses. Note that even if someday we stop needing
1712 to pause threads to access memory, we will need to be able to
1713 access registers, or other ptrace accesses like
1714 PTRACE_GET_THREAD_AREA. */
1716 /* Need to switch to each process in turn, because
1717 prepare_to_access_memory prepares for an access in the
1718 current process pointed to by general_thread. */
1719 switch_to_process (process
);
1720 cs
.general_thread
= current_thread
->id
;
1722 int res
= prepare_to_access_memory ();
1725 for_each_thread (process
->pid
, [&] (thread_info
*thread
)
1727 handle_qxfer_threads_worker (thread
, buffer
);
1730 done_accessing_memory ();
1737 buffer_grow_str0 (buffer
, "</threads>\n");
1738 return error_proc
== nullptr;
1741 /* Handle qXfer:threads:read. */
1744 handle_qxfer_threads (const char *annex
,
1745 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1746 ULONGEST offset
, LONGEST len
)
1748 static char *result
= 0;
1749 static unsigned int result_length
= 0;
1751 if (writebuf
!= NULL
)
1754 if (annex
[0] != '\0')
1759 struct buffer buffer
;
1760 /* When asked for data at offset 0, generate everything and store into
1761 'result'. Successive reads will be served off 'result'. */
1765 buffer_init (&buffer
);
1767 bool res
= handle_qxfer_threads_proper (&buffer
);
1769 result
= buffer_finish (&buffer
);
1770 result_length
= strlen (result
);
1771 buffer_free (&buffer
);
1777 if (offset
>= result_length
)
1779 /* We're out of data. */
1786 if (len
> result_length
- offset
)
1787 len
= result_length
- offset
;
1789 memcpy (readbuf
, result
+ offset
, len
);
1794 /* Handle qXfer:traceframe-info:read. */
1797 handle_qxfer_traceframe_info (const char *annex
,
1798 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1799 ULONGEST offset
, LONGEST len
)
1801 client_state
&cs
= get_client_state ();
1802 static char *result
= 0;
1803 static unsigned int result_length
= 0;
1805 if (writebuf
!= NULL
)
1808 if (!target_running () || annex
[0] != '\0' || cs
.current_traceframe
== -1)
1813 struct buffer buffer
;
1815 /* When asked for data at offset 0, generate everything and
1816 store into 'result'. Successive reads will be served off
1820 buffer_init (&buffer
);
1822 traceframe_read_info (cs
.current_traceframe
, &buffer
);
1824 result
= buffer_finish (&buffer
);
1825 result_length
= strlen (result
);
1826 buffer_free (&buffer
);
1829 if (offset
>= result_length
)
1831 /* We're out of data. */
1838 if (len
> result_length
- offset
)
1839 len
= result_length
- offset
;
1841 memcpy (readbuf
, result
+ offset
, len
);
1845 /* Handle qXfer:fdpic:read. */
1848 handle_qxfer_fdpic (const char *annex
, gdb_byte
*readbuf
,
1849 const gdb_byte
*writebuf
, ULONGEST offset
, LONGEST len
)
1851 if (!the_target
->supports_read_loadmap ())
1854 if (current_thread
== NULL
)
1857 return the_target
->read_loadmap (annex
, offset
, readbuf
, len
);
1860 /* Handle qXfer:btrace:read. */
1863 handle_qxfer_btrace (const char *annex
,
1864 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1865 ULONGEST offset
, LONGEST len
)
1867 client_state
&cs
= get_client_state ();
1868 static struct buffer cache
;
1869 struct thread_info
*thread
;
1870 enum btrace_read_type type
;
1873 if (writebuf
!= NULL
)
1876 if (cs
.general_thread
== null_ptid
1877 || cs
.general_thread
== minus_one_ptid
)
1879 strcpy (cs
.own_buf
, "E.Must select a single thread.");
1883 thread
= find_thread_ptid (cs
.general_thread
);
1886 strcpy (cs
.own_buf
, "E.No such thread.");
1890 if (thread
->btrace
== NULL
)
1892 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
1896 if (strcmp (annex
, "all") == 0)
1897 type
= BTRACE_READ_ALL
;
1898 else if (strcmp (annex
, "new") == 0)
1899 type
= BTRACE_READ_NEW
;
1900 else if (strcmp (annex
, "delta") == 0)
1901 type
= BTRACE_READ_DELTA
;
1904 strcpy (cs
.own_buf
, "E.Bad annex.");
1910 buffer_free (&cache
);
1914 result
= target_read_btrace (thread
->btrace
, &cache
, type
);
1916 memcpy (cs
.own_buf
, cache
.buffer
, cache
.used_size
);
1918 catch (const gdb_exception_error
&exception
)
1920 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
1927 else if (offset
> cache
.used_size
)
1929 buffer_free (&cache
);
1933 if (len
> cache
.used_size
- offset
)
1934 len
= cache
.used_size
- offset
;
1936 memcpy (readbuf
, cache
.buffer
+ offset
, len
);
1941 /* Handle qXfer:btrace-conf:read. */
1944 handle_qxfer_btrace_conf (const char *annex
,
1945 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1946 ULONGEST offset
, LONGEST len
)
1948 client_state
&cs
= get_client_state ();
1949 static struct buffer cache
;
1950 struct thread_info
*thread
;
1953 if (writebuf
!= NULL
)
1956 if (annex
[0] != '\0')
1959 if (cs
.general_thread
== null_ptid
1960 || cs
.general_thread
== minus_one_ptid
)
1962 strcpy (cs
.own_buf
, "E.Must select a single thread.");
1966 thread
= find_thread_ptid (cs
.general_thread
);
1969 strcpy (cs
.own_buf
, "E.No such thread.");
1973 if (thread
->btrace
== NULL
)
1975 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
1981 buffer_free (&cache
);
1985 result
= target_read_btrace_conf (thread
->btrace
, &cache
);
1987 memcpy (cs
.own_buf
, cache
.buffer
, cache
.used_size
);
1989 catch (const gdb_exception_error
&exception
)
1991 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
1998 else if (offset
> cache
.used_size
)
2000 buffer_free (&cache
);
2004 if (len
> cache
.used_size
- offset
)
2005 len
= cache
.used_size
- offset
;
2007 memcpy (readbuf
, cache
.buffer
+ offset
, len
);
2012 static const struct qxfer qxfer_packets
[] =
2014 { "auxv", handle_qxfer_auxv
},
2015 { "btrace", handle_qxfer_btrace
},
2016 { "btrace-conf", handle_qxfer_btrace_conf
},
2017 { "exec-file", handle_qxfer_exec_file
},
2018 { "fdpic", handle_qxfer_fdpic
},
2019 { "features", handle_qxfer_features
},
2020 { "libraries", handle_qxfer_libraries
},
2021 { "libraries-svr4", handle_qxfer_libraries_svr4
},
2022 { "osdata", handle_qxfer_osdata
},
2023 { "siginfo", handle_qxfer_siginfo
},
2024 { "statictrace", handle_qxfer_statictrace
},
2025 { "threads", handle_qxfer_threads
},
2026 { "traceframe-info", handle_qxfer_traceframe_info
},
2030 handle_qxfer (char *own_buf
, int packet_len
, int *new_packet_len_p
)
2038 if (!startswith (own_buf
, "qXfer:"))
2041 /* Grab the object, r/w and annex. */
2042 if (decode_xfer (own_buf
+ 6, &object
, &rw
, &annex
, &offset
) < 0)
2044 write_enn (own_buf
);
2049 i
< sizeof (qxfer_packets
) / sizeof (qxfer_packets
[0]);
2052 const struct qxfer
*q
= &qxfer_packets
[i
];
2054 if (strcmp (object
, q
->object
) == 0)
2056 if (strcmp (rw
, "read") == 0)
2058 unsigned char *data
;
2063 /* Grab the offset and length. */
2064 if (decode_xfer_read (offset
, &ofs
, &len
) < 0)
2066 write_enn (own_buf
);
2070 /* Read one extra byte, as an indicator of whether there is
2072 if (len
> PBUFSIZ
- 2)
2074 data
= (unsigned char *) malloc (len
+ 1);
2077 write_enn (own_buf
);
2080 n
= (*q
->xfer
) (annex
, data
, NULL
, ofs
, len
+ 1);
2088 /* Preserve error message. */
2091 write_enn (own_buf
);
2093 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, len
, 1);
2095 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, n
, 0);
2100 else if (strcmp (rw
, "write") == 0)
2105 unsigned char *data
;
2107 strcpy (own_buf
, "E00");
2108 data
= (unsigned char *) malloc (packet_len
- (offset
- own_buf
));
2111 write_enn (own_buf
);
2114 if (decode_xfer_write (offset
, packet_len
- (offset
- own_buf
),
2115 &ofs
, &len
, data
) < 0)
2118 write_enn (own_buf
);
2122 n
= (*q
->xfer
) (annex
, NULL
, data
, ofs
, len
);
2130 /* Preserve error message. */
2133 write_enn (own_buf
);
2135 sprintf (own_buf
, "%x", n
);
2148 /* Compute 32 bit CRC from inferior memory.
2150 On success, return 32 bit CRC.
2151 On failure, return (unsigned long long) -1. */
2153 static unsigned long long
2154 crc32 (CORE_ADDR base
, int len
, unsigned int crc
)
2158 unsigned char byte
= 0;
2160 /* Return failure if memory read fails. */
2161 if (read_inferior_memory (base
, &byte
, 1) != 0)
2162 return (unsigned long long) -1;
2164 crc
= xcrc32 (&byte
, 1, crc
);
2167 return (unsigned long long) crc
;
2170 /* Parse the qMemTags packet request into ADDR and LEN. */
2173 parse_fetch_memtags_request (char *request
, CORE_ADDR
*addr
, size_t *len
,
2176 gdb_assert (startswith (request
, "qMemTags:"));
2178 const char *p
= request
+ strlen ("qMemTags:");
2180 /* Read address and length. */
2181 unsigned int length
= 0;
2182 p
= decode_m_packet_params (p
, addr
, &length
, ':');
2185 /* Read the tag type. */
2186 ULONGEST tag_type
= 0;
2187 p
= unpack_varlen_hex (p
, &tag_type
);
2188 *type
= (int) tag_type
;
2191 /* Add supported btrace packets to BUF. */
2194 supported_btrace_packets (char *buf
)
2196 strcat (buf
, ";Qbtrace:bts+");
2197 strcat (buf
, ";Qbtrace-conf:bts:size+");
2198 strcat (buf
, ";Qbtrace:pt+");
2199 strcat (buf
, ";Qbtrace-conf:pt:size+");
2200 strcat (buf
, ";Qbtrace:off+");
2201 strcat (buf
, ";qXfer:btrace:read+");
2202 strcat (buf
, ";qXfer:btrace-conf:read+");
2205 /* Handle all of the extended 'q' packets. */
2208 handle_query (char *own_buf
, int packet_len
, int *new_packet_len_p
)
2210 client_state
&cs
= get_client_state ();
2211 static std::list
<thread_info
*>::const_iterator thread_iter
;
2213 /* Reply the current thread id. */
2214 if (strcmp ("qC", own_buf
) == 0 && !disable_packet_qC
)
2217 require_running_or_return (own_buf
);
2219 if (cs
.general_thread
!= null_ptid
&& cs
.general_thread
!= minus_one_ptid
)
2220 ptid
= cs
.general_thread
;
2223 thread_iter
= all_threads
.begin ();
2224 ptid
= (*thread_iter
)->id
;
2227 sprintf (own_buf
, "QC");
2229 write_ptid (own_buf
, ptid
);
2233 if (strcmp ("qSymbol::", own_buf
) == 0)
2235 scoped_restore_current_thread restore_thread
;
2237 /* For qSymbol, GDB only changes the current thread if the
2238 previous current thread was of a different process. So if
2239 the previous thread is gone, we need to pick another one of
2240 the same process. This can happen e.g., if we followed an
2241 exec in a non-leader thread. */
2242 if (current_thread
== NULL
)
2244 thread_info
*any_thread
2245 = find_any_thread_of_pid (cs
.general_thread
.pid ());
2246 switch_to_thread (any_thread
);
2248 /* Just in case, if we didn't find a thread, then bail out
2249 instead of crashing. */
2250 if (current_thread
== NULL
)
2252 write_enn (own_buf
);
2257 /* GDB is suggesting new symbols have been loaded. This may
2258 mean a new shared library has been detected as loaded, so
2259 take the opportunity to check if breakpoints we think are
2260 inserted, still are. Note that it isn't guaranteed that
2261 we'll see this when a shared library is loaded, and nor will
2262 we see this for unloads (although breakpoints in unloaded
2263 libraries shouldn't trigger), as GDB may not find symbols for
2264 the library at all. We also re-validate breakpoints when we
2265 see a second GDB breakpoint for the same address, and or when
2266 we access breakpoint shadows. */
2267 validate_breakpoints ();
2269 if (target_supports_tracepoints ())
2270 tracepoint_look_up_symbols ();
2272 if (current_thread
!= NULL
)
2273 the_target
->look_up_symbols ();
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
.set_signalled (GDB_SIGNAL_KILL
);
3153 cs
.last_ptid
= ptid_t (pid
);
3154 discard_queued_stop_replies (cs
.last_ptid
);
3158 write_enn (own_buf
);
3161 /* Handle all of the extended 'v' packets. */
3163 handle_v_requests (char *own_buf
, int packet_len
, int *new_packet_len
)
3165 client_state
&cs
= get_client_state ();
3166 if (!disable_packet_vCont
)
3168 if (strcmp (own_buf
, "vCtrlC") == 0)
3170 the_target
->request_interrupt ();
3175 if (startswith (own_buf
, "vCont;"))
3177 handle_v_cont (own_buf
);
3181 if (startswith (own_buf
, "vCont?"))
3183 strcpy (own_buf
, "vCont;c;C;t");
3185 if (target_supports_hardware_single_step ()
3186 || target_supports_software_single_step ()
3187 || !cs
.vCont_supported
)
3189 /* If target supports single step either by hardware or by
3190 software, add actions s and S to the list of supported
3191 actions. On the other hand, if GDB doesn't request the
3192 supported vCont actions in qSupported packet, add s and
3193 S to the list too. */
3194 own_buf
= own_buf
+ strlen (own_buf
);
3195 strcpy (own_buf
, ";s;S");
3198 if (target_supports_range_stepping ())
3200 own_buf
= own_buf
+ strlen (own_buf
);
3201 strcpy (own_buf
, ";r");
3207 if (startswith (own_buf
, "vFile:")
3208 && handle_vFile (own_buf
, packet_len
, new_packet_len
))
3211 if (startswith (own_buf
, "vAttach;"))
3213 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3215 fprintf (stderr
, "Already debugging a process\n");
3216 write_enn (own_buf
);
3219 handle_v_attach (own_buf
);
3223 if (startswith (own_buf
, "vRun;"))
3225 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3227 fprintf (stderr
, "Already debugging a process\n");
3228 write_enn (own_buf
);
3231 handle_v_run (own_buf
);
3235 if (startswith (own_buf
, "vKill;"))
3237 if (!target_running ())
3239 fprintf (stderr
, "No process to kill\n");
3240 write_enn (own_buf
);
3243 handle_v_kill (own_buf
);
3247 if (handle_notif_ack (own_buf
, packet_len
))
3250 /* Otherwise we didn't know what packet it was. Say we didn't
3256 /* Resume thread and wait for another event. In non-stop mode,
3257 don't really wait here, but return immediatelly to the event
3260 myresume (char *own_buf
, int step
, int sig
)
3262 client_state
&cs
= get_client_state ();
3263 struct thread_resume resume_info
[2];
3265 int valid_cont_thread
;
3267 valid_cont_thread
= (cs
.cont_thread
!= null_ptid
3268 && cs
.cont_thread
!= minus_one_ptid
);
3270 if (step
|| sig
|| valid_cont_thread
)
3272 resume_info
[0].thread
= current_ptid
;
3274 resume_info
[0].kind
= resume_step
;
3276 resume_info
[0].kind
= resume_continue
;
3277 resume_info
[0].sig
= sig
;
3281 if (!valid_cont_thread
)
3283 resume_info
[n
].thread
= minus_one_ptid
;
3284 resume_info
[n
].kind
= resume_continue
;
3285 resume_info
[n
].sig
= 0;
3289 resume (resume_info
, n
);
3292 /* Callback for for_each_thread. Make a new stop reply for each
3296 queue_stop_reply_callback (thread_info
*thread
)
3298 /* For now, assume targets that don't have this callback also don't
3299 manage the thread's last_status field. */
3300 if (!the_target
->supports_thread_stopped ())
3302 struct vstop_notif
*new_notif
= new struct vstop_notif
;
3304 new_notif
->ptid
= thread
->id
;
3305 new_notif
->status
= thread
->last_status
;
3306 /* Pass the last stop reply back to GDB, but don't notify
3308 notif_event_enque (¬if_stop
, new_notif
);
3312 if (target_thread_stopped (thread
))
3314 threads_debug_printf
3315 ("Reporting thread %s as already stopped with %s",
3316 target_pid_to_str (thread
->id
).c_str (),
3317 thread
->last_status
.to_string ().c_str ());
3319 gdb_assert (thread
->last_status
.kind () != TARGET_WAITKIND_IGNORE
);
3321 /* Pass the last stop reply back to GDB, but don't notify
3323 queue_stop_reply (thread
->id
, thread
->last_status
);
3328 /* Set this inferior threads's state as "want-stopped". We won't
3329 resume this thread until the client gives us another action for
3333 gdb_wants_thread_stopped (thread_info
*thread
)
3335 thread
->last_resume_kind
= resume_stop
;
3337 if (thread
->last_status
.kind () == TARGET_WAITKIND_IGNORE
)
3339 /* Most threads are stopped implicitly (all-stop); tag that with
3341 thread
->last_status
.set_stopped (GDB_SIGNAL_0
);
3345 /* Set all threads' states as "want-stopped". */
3348 gdb_wants_all_threads_stopped (void)
3350 for_each_thread (gdb_wants_thread_stopped
);
3353 /* Callback for for_each_thread. If the thread is stopped with an
3354 interesting event, mark it as having a pending event. */
3357 set_pending_status_callback (thread_info
*thread
)
3359 if (thread
->last_status
.kind () != TARGET_WAITKIND_STOPPED
3360 || (thread
->last_status
.sig () != GDB_SIGNAL_0
3361 /* A breakpoint, watchpoint or finished step from a previous
3362 GDB run isn't considered interesting for a new GDB run.
3363 If we left those pending, the new GDB could consider them
3364 random SIGTRAPs. This leaves out real async traps. We'd
3365 have to peek into the (target-specific) siginfo to
3366 distinguish those. */
3367 && thread
->last_status
.sig () != GDB_SIGNAL_TRAP
))
3368 thread
->status_pending_p
= 1;
3371 /* Status handler for the '?' packet. */
3374 handle_status (char *own_buf
)
3376 client_state
&cs
= get_client_state ();
3378 /* GDB is connected, don't forward events to the target anymore. */
3379 for_each_process ([] (process_info
*process
) {
3380 process
->gdb_detached
= 0;
3383 /* In non-stop mode, we must send a stop reply for each stopped
3384 thread. In all-stop mode, just send one for the first stopped
3389 for_each_thread (queue_stop_reply_callback
);
3391 /* The first is sent immediatly. OK is sent if there is no
3392 stopped thread, which is the same handling of the vStopped
3393 packet (by design). */
3394 notif_write_event (¬if_stop
, cs
.own_buf
);
3398 thread_info
*thread
= NULL
;
3400 target_pause_all (false);
3401 target_stabilize_threads ();
3402 gdb_wants_all_threads_stopped ();
3404 /* We can only report one status, but we might be coming out of
3405 non-stop -- if more than one thread is stopped with
3406 interesting events, leave events for the threads we're not
3407 reporting now pending. They'll be reported the next time the
3408 threads are resumed. Start by marking all interesting events
3410 for_each_thread (set_pending_status_callback
);
3412 /* Prefer the last thread that reported an event to GDB (even if
3413 that was a GDB_SIGNAL_TRAP). */
3414 if (cs
.last_status
.kind () != TARGET_WAITKIND_IGNORE
3415 && cs
.last_status
.kind () != TARGET_WAITKIND_EXITED
3416 && cs
.last_status
.kind () != TARGET_WAITKIND_SIGNALLED
)
3417 thread
= find_thread_ptid (cs
.last_ptid
);
3419 /* If the last event thread is not found for some reason, look
3420 for some other thread that might have an event to report. */
3422 thread
= find_thread ([] (thread_info
*thr_arg
)
3424 return thr_arg
->status_pending_p
;
3427 /* If we're still out of luck, simply pick the first thread in
3430 thread
= get_first_thread ();
3434 struct thread_info
*tp
= (struct thread_info
*) thread
;
3436 /* We're reporting this event, so it's no longer
3438 tp
->status_pending_p
= 0;
3440 /* GDB assumes the current thread is the thread we're
3441 reporting the status for. */
3442 cs
.general_thread
= thread
->id
;
3443 set_desired_thread ();
3445 gdb_assert (tp
->last_status
.kind () != TARGET_WAITKIND_IGNORE
);
3446 prepare_resume_reply (own_buf
, tp
->id
, tp
->last_status
);
3449 strcpy (own_buf
, "W00");
3454 gdbserver_version (void)
3456 printf ("GNU gdbserver %s%s\n"
3457 "Copyright (C) 2022 Free Software Foundation, Inc.\n"
3458 "gdbserver is free software, covered by the "
3459 "GNU General Public License.\n"
3460 "This gdbserver was configured as \"%s\"\n",
3461 PKGVERSION
, version
, host_name
);
3465 gdbserver_usage (FILE *stream
)
3467 fprintf (stream
, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3468 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3469 "\tgdbserver [OPTIONS] --multi COMM\n"
3471 "COMM may either be a tty device (for serial debugging),\n"
3472 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3473 "stdin/stdout of gdbserver.\n"
3474 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3475 "PID is the process ID to attach to, when --attach is specified.\n"
3477 "Operating modes:\n"
3479 " --attach Attach to running process PID.\n"
3480 " --multi Start server without a specific program, and\n"
3481 " only quit when explicitly commanded.\n"
3482 " --once Exit after the first connection has closed.\n"
3483 " --help Print this message and then exit.\n"
3484 " --version Display version information and exit.\n"
3488 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3489 " --disable-randomization\n"
3490 " Run PROG with address space randomization disabled.\n"
3491 " --no-disable-randomization\n"
3492 " Don't disable address space randomization when\n"
3494 " --startup-with-shell\n"
3495 " Start PROG using a shell. I.e., execs a shell that\n"
3496 " then execs PROG. (default)\n"
3497 " --no-startup-with-shell\n"
3498 " Exec PROG directly instead of using a shell.\n"
3499 " Disables argument globbing and variable substitution\n"
3500 " on UNIX-like systems.\n"
3504 " --debug Enable general debugging output.\n"
3505 " --debug-format=OPT1[,OPT2,...]\n"
3506 " Specify extra content in debugging output.\n"
3511 " --remote-debug Enable remote protocol debugging output.\n"
3512 " --event-loop-debug Enable event loop debugging output.\n"
3513 " --disable-packet=OPT1[,OPT2,...]\n"
3514 " Disable support for RSP packets or features.\n"
3516 " vCont, T, Tthread, qC, qfThreadInfo and \n"
3517 " threads (disable all threading packets).\n"
3519 "For more information, consult the GDB manual (available as on-line \n"
3520 "info or a printed manual).\n");
3521 if (REPORT_BUGS_TO
[0] && stream
== stdout
)
3522 fprintf (stream
, "Report bugs to \"%s\".\n", REPORT_BUGS_TO
);
3526 gdbserver_show_disableable (FILE *stream
)
3528 fprintf (stream
, "Disableable packets:\n"
3529 " vCont \tAll vCont packets\n"
3530 " qC \tQuerying the current thread\n"
3531 " qfThreadInfo\tThread listing\n"
3532 " Tthread \tPassing the thread specifier in the "
3533 "T stop reply packet\n"
3534 " threads \tAll of the above\n"
3535 " T \tAll 'T' packets\n");
3538 /* Start up the event loop. This is the entry point to the event
3544 /* Loop until there is nothing to do. This is the entry point to
3545 the event loop engine. If nothing is ready at this time, wait
3546 for something to happen (via wait_for_event), then process it.
3547 Return when there are no longer event sources to wait for. */
3549 keep_processing_events
= true;
3550 while (keep_processing_events
)
3552 /* Any events already waiting in the queue? */
3553 int res
= gdb_do_one_event ();
3555 /* Was there an error? */
3560 /* We are done with the event loop. There are no more event sources
3561 to listen to. So we exit gdbserver. */
3565 kill_inferior_callback (process_info
*process
)
3567 kill_inferior (process
);
3568 discard_queued_stop_replies (ptid_t (process
->pid
));
3571 /* Call this when exiting gdbserver with possible inferiors that need
3572 to be killed or detached from. */
3575 detach_or_kill_for_exit (void)
3577 /* First print a list of the inferiors we will be killing/detaching.
3578 This is to assist the user, for example, in case the inferior unexpectedly
3579 dies after we exit: did we screw up or did the inferior exit on its own?
3580 Having this info will save some head-scratching. */
3582 if (have_started_inferiors_p ())
3584 fprintf (stderr
, "Killing process(es):");
3586 for_each_process ([] (process_info
*process
) {
3587 if (!process
->attached
)
3588 fprintf (stderr
, " %d", process
->pid
);
3591 fprintf (stderr
, "\n");
3593 if (have_attached_inferiors_p ())
3595 fprintf (stderr
, "Detaching process(es):");
3597 for_each_process ([] (process_info
*process
) {
3598 if (process
->attached
)
3599 fprintf (stderr
, " %d", process
->pid
);
3602 fprintf (stderr
, "\n");
3605 /* Now we can kill or detach the inferiors. */
3606 for_each_process ([] (process_info
*process
) {
3607 int pid
= process
->pid
;
3609 if (process
->attached
)
3610 detach_inferior (process
);
3612 kill_inferior (process
);
3614 discard_queued_stop_replies (ptid_t (pid
));
3618 /* Value that will be passed to exit(3) when gdbserver exits. */
3619 static int exit_code
;
3621 /* Wrapper for detach_or_kill_for_exit that catches and prints
3625 detach_or_kill_for_exit_cleanup ()
3629 detach_or_kill_for_exit ();
3631 catch (const gdb_exception
&exception
)
3634 fprintf (stderr
, "Detach or kill failed: %s\n",
3642 namespace selftests
{
3645 test_memory_tagging_functions (void)
3647 /* Setup testing. */
3648 gdb::char_vector packet
;
3649 gdb::byte_vector tags
, bv
;
3650 std::string expected
;
3651 packet
.resize (32000);
3656 /* Test parsing a qMemTags request. */
3658 /* Valid request, addr, len and type updated. */
3662 strcpy (packet
.data (), "qMemTags:0,0:0");
3663 parse_fetch_memtags_request (packet
.data (), &addr
, &len
, &type
);
3664 SELF_CHECK (addr
== 0 && len
== 0 && type
== 0);
3666 /* Valid request, addr, len and type updated. */
3670 strcpy (packet
.data (), "qMemTags:deadbeef,ff:5");
3671 parse_fetch_memtags_request (packet
.data (), &addr
, &len
, &type
);
3672 SELF_CHECK (addr
== 0xdeadbeef && len
== 255 && type
== 5);
3674 /* Test creating a qMemTags reply. */
3676 /* Non-empty tag data. */
3679 for (int i
= 0; i
< 5; i
++)
3682 expected
= "m0001020304";
3683 SELF_CHECK (create_fetch_memtags_reply (packet
.data (), bv
) == true);
3684 SELF_CHECK (strcmp (packet
.data (), expected
.c_str ()) == 0);
3686 /* Test parsing a QMemTags request. */
3688 /* Valid request and empty tag data: addr, len, type and tags updated. */
3693 strcpy (packet
.data (), "QMemTags:0,0:0:");
3694 SELF_CHECK (parse_store_memtags_request (packet
.data (),
3695 &addr
, &len
, tags
, &type
) == true);
3696 SELF_CHECK (addr
== 0 && len
== 0 && type
== 0 && tags
.size () == 0);
3698 /* Valid request and non-empty tag data: addr, len, type
3699 and tags updated. */
3704 strcpy (packet
.data (),
3705 "QMemTags:deadbeef,ff:5:0001020304");
3706 SELF_CHECK (parse_store_memtags_request (packet
.data (), &addr
, &len
, tags
,
3708 SELF_CHECK (addr
== 0xdeadbeef && len
== 255 && type
== 5
3709 && tags
.size () == 5);
3712 } // namespace selftests
3713 #endif /* GDB_SELF_TEST */
3715 /* Main function. This is called by the real "main" function,
3716 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
3718 static void ATTRIBUTE_NORETURN
3719 captured_main (int argc
, char *argv
[])
3724 const char *port
= NULL
;
3725 char **next_arg
= &argv
[1];
3726 volatile int multi_mode
= 0;
3727 volatile int attach
= 0;
3729 bool selftest
= false;
3731 std::vector
<const char *> selftest_filters
;
3733 selftests::register_test ("remote_memory_tagging",
3734 selftests::test_memory_tagging_functions
);
3737 current_directory
= getcwd (NULL
, 0);
3738 client_state
&cs
= get_client_state ();
3740 if (current_directory
== NULL
)
3742 error (_("Could not find current working directory: %s"),
3743 safe_strerror (errno
));
3746 while (*next_arg
!= NULL
&& **next_arg
== '-')
3748 if (strcmp (*next_arg
, "--version") == 0)
3750 gdbserver_version ();
3753 else if (strcmp (*next_arg
, "--help") == 0)
3755 gdbserver_usage (stdout
);
3758 else if (strcmp (*next_arg
, "--attach") == 0)
3760 else if (strcmp (*next_arg
, "--multi") == 0)
3762 else if (strcmp (*next_arg
, "--wrapper") == 0)
3769 while (*next_arg
!= NULL
&& strcmp (*next_arg
, "--") != 0)
3771 wrapper_argv
+= *next_arg
;
3772 wrapper_argv
+= ' ';
3776 if (!wrapper_argv
.empty ())
3778 /* Erase the last whitespace. */
3779 wrapper_argv
.erase (wrapper_argv
.end () - 1);
3782 if (next_arg
== tmp
|| *next_arg
== NULL
)
3784 gdbserver_usage (stderr
);
3788 /* Consume the "--". */
3791 else if (strcmp (*next_arg
, "--debug") == 0)
3792 debug_threads
= true;
3793 else if (startswith (*next_arg
, "--debug-format="))
3795 std::string error_msg
3796 = parse_debug_format_options ((*next_arg
)
3797 + sizeof ("--debug-format=") - 1, 0);
3799 if (!error_msg
.empty ())
3801 fprintf (stderr
, "%s", error_msg
.c_str ());
3805 else if (strcmp (*next_arg
, "--remote-debug") == 0)
3806 remote_debug
= true;
3807 else if (strcmp (*next_arg
, "--event-loop-debug") == 0)
3808 debug_event_loop
= debug_event_loop_kind::ALL
;
3809 else if (startswith (*next_arg
, "--debug-file="))
3810 debug_set_output ((*next_arg
) + sizeof ("--debug-file=") -1);
3811 else if (strcmp (*next_arg
, "--disable-packet") == 0)
3813 gdbserver_show_disableable (stdout
);
3816 else if (startswith (*next_arg
, "--disable-packet="))
3818 char *packets
= *next_arg
+= sizeof ("--disable-packet=") - 1;
3820 for (char *tok
= strtok_r (packets
, ",", &saveptr
);
3822 tok
= strtok_r (NULL
, ",", &saveptr
))
3824 if (strcmp ("vCont", tok
) == 0)
3825 disable_packet_vCont
= true;
3826 else if (strcmp ("Tthread", tok
) == 0)
3827 disable_packet_Tthread
= true;
3828 else if (strcmp ("qC", tok
) == 0)
3829 disable_packet_qC
= true;
3830 else if (strcmp ("qfThreadInfo", tok
) == 0)
3831 disable_packet_qfThreadInfo
= true;
3832 else if (strcmp ("T", tok
) == 0)
3833 disable_packet_T
= true;
3834 else if (strcmp ("threads", tok
) == 0)
3836 disable_packet_vCont
= true;
3837 disable_packet_Tthread
= true;
3838 disable_packet_qC
= true;
3839 disable_packet_qfThreadInfo
= true;
3843 fprintf (stderr
, "Don't know how to disable \"%s\".\n\n",
3845 gdbserver_show_disableable (stderr
);
3850 else if (strcmp (*next_arg
, "-") == 0)
3852 /* "-" specifies a stdio connection and is a form of port
3854 port
= STDIO_CONNECTION_NAME
;
3858 else if (strcmp (*next_arg
, "--disable-randomization") == 0)
3859 cs
.disable_randomization
= 1;
3860 else if (strcmp (*next_arg
, "--no-disable-randomization") == 0)
3861 cs
.disable_randomization
= 0;
3862 else if (strcmp (*next_arg
, "--startup-with-shell") == 0)
3863 startup_with_shell
= true;
3864 else if (strcmp (*next_arg
, "--no-startup-with-shell") == 0)
3865 startup_with_shell
= false;
3866 else if (strcmp (*next_arg
, "--once") == 0)
3868 else if (strcmp (*next_arg
, "--selftest") == 0)
3870 else if (startswith (*next_arg
, "--selftest="))
3875 const char *filter
= *next_arg
+ strlen ("--selftest=");
3876 if (*filter
== '\0')
3878 fprintf (stderr
, _("Error: selftest filter is empty.\n"));
3882 selftest_filters
.push_back (filter
);
3887 fprintf (stderr
, "Unknown argument: %s\n", *next_arg
);
3900 if ((port
== NULL
|| (!attach
&& !multi_mode
&& *next_arg
== NULL
))
3903 gdbserver_usage (stderr
);
3907 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
3908 opened by remote_prepare. */
3911 save_original_signals_state (false);
3913 /* We need to know whether the remote connection is stdio before
3914 starting the inferior. Inferiors created in this scenario have
3915 stdin,stdout redirected. So do this here before we call
3918 remote_prepare (port
);
3923 /* --attach used to come after PORT, so allow it there for
3925 if (*next_arg
!= NULL
&& strcmp (*next_arg
, "--attach") == 0)
3932 && (*next_arg
== NULL
3933 || (*next_arg
)[0] == '\0'
3934 || (pid
= strtoul (*next_arg
, &arg_end
, 0)) == 0
3936 || next_arg
[1] != NULL
))
3941 gdbserver_usage (stderr
);
3945 /* Gather information about the environment. */
3946 our_environ
= gdb_environ::from_host_environ ();
3948 initialize_async_io ();
3950 have_job_control ();
3951 if (target_supports_tracepoints ())
3952 initialize_tracepoint ();
3954 mem_buf
= (unsigned char *) xmalloc (PBUFSIZ
);
3959 selftests::run_tests (selftest_filters
);
3961 printf (_("Selftests have been disabled for this build.\n"));
3963 throw_quit ("Quit");
3966 if (pid
== 0 && *next_arg
!= NULL
)
3970 n
= argc
- (next_arg
- argv
);
3971 program_path
.set (make_unique_xstrdup (next_arg
[0]));
3972 for (i
= 1; i
< n
; i
++)
3973 program_args
.push_back (xstrdup (next_arg
[i
]));
3975 /* Wait till we are at first instruction in program. */
3976 target_create_inferior (program_path
.get (), program_args
);
3978 /* We are now (hopefully) stopped at the first instruction of
3979 the target process. This assumes that the target process was
3980 successfully created. */
3984 if (attach_inferior (pid
) == -1)
3985 error ("Attaching not supported on this target");
3987 /* Otherwise succeeded. */
3991 cs
.last_status
.set_exited (0);
3992 cs
.last_ptid
= minus_one_ptid
;
3995 SCOPE_EXIT
{ detach_or_kill_for_exit_cleanup (); };
3997 /* Don't report shared library events on the initial connection,
3998 even if some libraries are preloaded. Avoids the "stopped by
3999 shared library event" notice on gdb side. */
4000 if (current_thread
!= nullptr)
4001 current_process ()->dlls_changed
= false;
4003 if (cs
.last_status
.kind () == TARGET_WAITKIND_EXITED
4004 || cs
.last_status
.kind () == TARGET_WAITKIND_SIGNALLED
)
4009 if (!was_running
&& !multi_mode
)
4010 error ("No program to debug");
4015 cs
.multi_process
= 0;
4016 cs
.report_fork_events
= 0;
4017 cs
.report_vfork_events
= 0;
4018 cs
.report_exec_events
= 0;
4019 /* Be sure we're out of tfind mode. */
4020 cs
.current_traceframe
= -1;
4021 cs
.cont_thread
= null_ptid
;
4022 cs
.swbreak_feature
= 0;
4023 cs
.hwbreak_feature
= 0;
4024 cs
.vCont_supported
= 0;
4025 cs
.memory_tagging_feature
= false;
4031 /* Wait for events. This will return when all event sources
4032 are removed from the event loop. */
4033 start_event_loop ();
4035 /* If an exit was requested (using the "monitor exit"
4036 command), terminate now. */
4038 throw_quit ("Quit");
4040 /* The only other way to get here is for getpkt to fail:
4042 - If --once was specified, we're done.
4044 - If not in extended-remote mode, and we're no longer
4045 debugging anything, simply exit: GDB has disconnected
4046 after processing the last process exit.
4048 - Otherwise, close the connection and reopen it at the
4050 if (run_once
|| (!extended_protocol
&& !target_running ()))
4051 throw_quit ("Quit");
4054 "Remote side has terminated connection. "
4055 "GDBserver will reopen the connection.\n");
4057 /* Get rid of any pending statuses. An eventual reconnection
4058 (by the same GDB instance or another) will refresh all its
4059 state from scratch. */
4060 discard_queued_stop_replies (minus_one_ptid
);
4061 for_each_thread ([] (thread_info
*thread
)
4063 thread
->status_pending_p
= 0;
4068 if (disconnected_tracing
)
4070 /* Try to enable non-stop/async mode, so we we can
4071 both wait for an async socket accept, and handle
4072 async target events simultaneously. There's also
4073 no point either in having the target always stop
4074 all threads, when we're going to pass signals
4075 down without informing GDB. */
4078 if (the_target
->start_non_stop (true))
4081 /* Detaching implicitly resumes all threads;
4082 simply disconnecting does not. */
4088 "Disconnected tracing disabled; "
4089 "stopping trace run.\n");
4094 catch (const gdb_exception_error
&exception
)
4097 fprintf (stderr
, "gdbserver: %s\n", exception
.what ());
4099 if (response_needed
)
4101 write_enn (cs
.own_buf
);
4102 putpkt (cs
.own_buf
);
4106 throw_quit ("Quit");
4111 /* Main function. */
4114 main (int argc
, char *argv
[])
4119 captured_main (argc
, argv
);
4121 catch (const gdb_exception
&exception
)
4123 if (exception
.reason
== RETURN_ERROR
)
4126 fprintf (stderr
, "%s\n", exception
.what ());
4127 fprintf (stderr
, "Exiting\n");
4134 gdb_assert_not_reached ("captured_main should never return");
4137 /* Process options coming from Z packets for a breakpoint. PACKET is
4138 the packet buffer. *PACKET is updated to point to the first char
4139 after the last processed option. */
4142 process_point_options (struct gdb_breakpoint
*bp
, const char **packet
)
4144 const char *dataptr
= *packet
;
4147 /* Check if data has the correct format. */
4148 if (*dataptr
!= ';')
4155 if (*dataptr
== ';')
4158 if (*dataptr
== 'X')
4160 /* Conditional expression. */
4161 threads_debug_printf ("Found breakpoint condition.");
4162 if (!add_breakpoint_condition (bp
, &dataptr
))
4163 dataptr
= strchrnul (dataptr
, ';');
4165 else if (startswith (dataptr
, "cmds:"))
4167 dataptr
+= strlen ("cmds:");
4168 threads_debug_printf ("Found breakpoint commands %s.", dataptr
);
4169 persist
= (*dataptr
== '1');
4171 if (add_breakpoint_commands (bp
, &dataptr
, persist
))
4172 dataptr
= strchrnul (dataptr
, ';');
4176 fprintf (stderr
, "Unknown token %c, ignoring.\n",
4178 /* Skip tokens until we find one that we recognize. */
4179 dataptr
= strchrnul (dataptr
, ';');
4185 /* Event loop callback that handles a serial event. The first byte in
4186 the serial buffer gets us here. We expect characters to arrive at
4187 a brisk pace, so we read the rest of the packet with a blocking
4191 process_serial_event (void)
4193 client_state
&cs
= get_client_state ();
4199 int new_packet_len
= -1;
4201 disable_async_io ();
4203 response_needed
= false;
4204 packet_len
= getpkt (cs
.own_buf
);
4205 if (packet_len
<= 0)
4208 /* Force an event loop break. */
4211 response_needed
= true;
4213 char ch
= cs
.own_buf
[0];
4217 handle_query (cs
.own_buf
, packet_len
, &new_packet_len
);
4220 handle_general_set (cs
.own_buf
);
4223 handle_detach (cs
.own_buf
);
4226 extended_protocol
= true;
4227 write_ok (cs
.own_buf
);
4230 handle_status (cs
.own_buf
);
4233 if (cs
.own_buf
[1] == 'c' || cs
.own_buf
[1] == 'g' || cs
.own_buf
[1] == 's')
4235 require_running_or_break (cs
.own_buf
);
4237 ptid_t thread_id
= read_ptid (&cs
.own_buf
[2], NULL
);
4239 if (thread_id
== null_ptid
|| thread_id
== minus_one_ptid
)
4240 thread_id
= null_ptid
;
4241 else if (thread_id
.is_pid ())
4243 /* The ptid represents a pid. */
4244 thread_info
*thread
= find_any_thread_of_pid (thread_id
.pid ());
4248 write_enn (cs
.own_buf
);
4252 thread_id
= thread
->id
;
4256 /* The ptid represents a lwp/tid. */
4257 if (find_thread_ptid (thread_id
) == NULL
)
4259 write_enn (cs
.own_buf
);
4264 if (cs
.own_buf
[1] == 'g')
4266 if (thread_id
== null_ptid
)
4268 /* GDB is telling us to choose any thread. Check if
4269 the currently selected thread is still valid. If
4270 it is not, select the first available. */
4271 thread_info
*thread
= find_thread_ptid (cs
.general_thread
);
4273 thread
= get_first_thread ();
4274 thread_id
= thread
->id
;
4277 cs
.general_thread
= thread_id
;
4278 set_desired_thread ();
4279 gdb_assert (current_thread
!= NULL
);
4281 else if (cs
.own_buf
[1] == 'c')
4282 cs
.cont_thread
= thread_id
;
4284 write_ok (cs
.own_buf
);
4288 /* Silently ignore it so that gdb can extend the protocol
4289 without compatibility headaches. */
4290 cs
.own_buf
[0] = '\0';
4294 require_running_or_break (cs
.own_buf
);
4295 if (cs
.current_traceframe
>= 0)
4297 struct regcache
*regcache
4298 = new_register_cache (current_target_desc ());
4300 if (fetch_traceframe_registers (cs
.current_traceframe
,
4302 registers_to_string (regcache
, cs
.own_buf
);
4304 write_enn (cs
.own_buf
);
4305 free_register_cache (regcache
);
4309 struct regcache
*regcache
;
4311 if (!set_desired_thread ())
4312 write_enn (cs
.own_buf
);
4315 regcache
= get_thread_regcache (current_thread
, 1);
4316 registers_to_string (regcache
, cs
.own_buf
);
4321 require_running_or_break (cs
.own_buf
);
4322 if (cs
.current_traceframe
>= 0)
4323 write_enn (cs
.own_buf
);
4326 struct regcache
*regcache
;
4328 if (!set_desired_thread ())
4329 write_enn (cs
.own_buf
);
4332 regcache
= get_thread_regcache (current_thread
, 1);
4333 registers_from_string (regcache
, &cs
.own_buf
[1]);
4334 write_ok (cs
.own_buf
);
4340 require_running_or_break (cs
.own_buf
);
4341 decode_m_packet (&cs
.own_buf
[1], &mem_addr
, &len
);
4342 int res
= gdb_read_memory (mem_addr
, mem_buf
, len
);
4344 write_enn (cs
.own_buf
);
4346 bin2hex (mem_buf
, cs
.own_buf
, res
);
4350 require_running_or_break (cs
.own_buf
);
4351 decode_M_packet (&cs
.own_buf
[1], &mem_addr
, &len
, &mem_buf
);
4352 if (gdb_write_memory (mem_addr
, mem_buf
, len
) == 0)
4353 write_ok (cs
.own_buf
);
4355 write_enn (cs
.own_buf
);
4358 require_running_or_break (cs
.own_buf
);
4359 if (decode_X_packet (&cs
.own_buf
[1], packet_len
- 1,
4360 &mem_addr
, &len
, &mem_buf
) < 0
4361 || gdb_write_memory (mem_addr
, mem_buf
, len
) != 0)
4362 write_enn (cs
.own_buf
);
4364 write_ok (cs
.own_buf
);
4367 require_running_or_break (cs
.own_buf
);
4368 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4369 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4370 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4373 myresume (cs
.own_buf
, 0, signal
);
4376 require_running_or_break (cs
.own_buf
);
4377 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4378 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4379 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4382 myresume (cs
.own_buf
, 1, signal
);
4385 require_running_or_break (cs
.own_buf
);
4387 myresume (cs
.own_buf
, 0, signal
);
4390 require_running_or_break (cs
.own_buf
);
4392 myresume (cs
.own_buf
, 1, signal
);
4394 case 'Z': /* insert_ ... */
4396 case 'z': /* remove_ ... */
4401 char type
= cs
.own_buf
[1];
4403 const int insert
= ch
== 'Z';
4404 const char *p
= &cs
.own_buf
[3];
4406 p
= unpack_varlen_hex (p
, &addr
);
4407 kind
= strtol (p
+ 1, &dataptr
, 16);
4411 struct gdb_breakpoint
*bp
;
4413 bp
= set_gdb_breakpoint (type
, addr
, kind
, &res
);
4418 /* GDB may have sent us a list of *point parameters to
4419 be evaluated on the target's side. Read such list
4420 here. If we already have a list of parameters, GDB
4421 is telling us to drop that list and use this one
4423 clear_breakpoint_conditions_and_commands (bp
);
4424 const char *options
= dataptr
;
4425 process_point_options (bp
, &options
);
4429 res
= delete_gdb_breakpoint (type
, addr
, kind
);
4432 write_ok (cs
.own_buf
);
4435 cs
.own_buf
[0] = '\0';
4437 write_enn (cs
.own_buf
);
4441 response_needed
= false;
4442 if (!target_running ())
4443 /* The packet we received doesn't make sense - but we can't
4444 reply to it, either. */
4447 fprintf (stderr
, "Killing all inferiors\n");
4449 for_each_process (kill_inferior_callback
);
4451 /* When using the extended protocol, we wait with no program
4452 running. The traditional protocol will exit instead. */
4453 if (extended_protocol
)
4455 cs
.last_status
.set_exited (GDB_SIGNAL_KILL
);
4463 require_running_or_break (cs
.own_buf
);
4465 ptid_t thread_id
= read_ptid (&cs
.own_buf
[1], NULL
);
4466 if (find_thread_ptid (thread_id
) == NULL
)
4468 write_enn (cs
.own_buf
);
4472 if (mythread_alive (thread_id
))
4473 write_ok (cs
.own_buf
);
4475 write_enn (cs
.own_buf
);
4479 response_needed
= false;
4481 /* Restarting the inferior is only supported in the extended
4483 if (extended_protocol
)
4485 if (target_running ())
4486 for_each_process (kill_inferior_callback
);
4488 fprintf (stderr
, "GDBserver restarting\n");
4490 /* Wait till we are at 1st instruction in prog. */
4491 if (program_path
.get () != NULL
)
4493 target_create_inferior (program_path
.get (), program_args
);
4495 if (cs
.last_status
.kind () == TARGET_WAITKIND_STOPPED
)
4497 /* Stopped at the first instruction of the target
4499 cs
.general_thread
= cs
.last_ptid
;
4503 /* Something went wrong. */
4504 cs
.general_thread
= null_ptid
;
4509 cs
.last_status
.set_exited (GDB_SIGNAL_KILL
);
4515 /* It is a request we don't understand. Respond with an
4516 empty packet so that gdb knows that we don't support this
4518 cs
.own_buf
[0] = '\0';
4522 /* Extended (long) request. */
4523 handle_v_requests (cs
.own_buf
, packet_len
, &new_packet_len
);
4527 /* It is a request we don't understand. Respond with an empty
4528 packet so that gdb knows that we don't support this
4530 cs
.own_buf
[0] = '\0';
4534 if (new_packet_len
!= -1)
4535 putpkt_binary (cs
.own_buf
, new_packet_len
);
4537 putpkt (cs
.own_buf
);
4539 response_needed
= false;
4547 /* Event-loop callback for serial events. */
4550 handle_serial_event (int err
, gdb_client_data client_data
)
4552 threads_debug_printf ("handling possible serial event");
4554 /* Really handle it. */
4555 if (process_serial_event () < 0)
4557 keep_processing_events
= false;
4561 /* Be sure to not change the selected thread behind GDB's back.
4562 Important in the non-stop mode asynchronous protocol. */
4563 set_desired_thread ();
4566 /* Push a stop notification on the notification queue. */
4569 push_stop_notification (ptid_t ptid
, const target_waitstatus
&status
)
4571 struct vstop_notif
*vstop_notif
= new struct vstop_notif
;
4573 vstop_notif
->status
= status
;
4574 vstop_notif
->ptid
= ptid
;
4575 /* Push Stop notification. */
4576 notif_push (¬if_stop
, vstop_notif
);
4579 /* Event-loop callback for target events. */
4582 handle_target_event (int err
, gdb_client_data client_data
)
4584 client_state
&cs
= get_client_state ();
4585 threads_debug_printf ("handling possible target event");
4587 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
,
4590 if (cs
.last_status
.kind () == TARGET_WAITKIND_NO_RESUMED
)
4592 if (gdb_connected () && report_no_resumed
)
4593 push_stop_notification (null_ptid
, cs
.last_status
);
4595 else if (cs
.last_status
.kind () != TARGET_WAITKIND_IGNORE
)
4597 int pid
= cs
.last_ptid
.pid ();
4598 struct process_info
*process
= find_process_pid (pid
);
4599 int forward_event
= !gdb_connected () || process
->gdb_detached
;
4601 if (cs
.last_status
.kind () == TARGET_WAITKIND_EXITED
4602 || cs
.last_status
.kind () == TARGET_WAITKIND_SIGNALLED
)
4604 mark_breakpoints_out (process
);
4605 target_mourn_inferior (cs
.last_ptid
);
4607 else if (cs
.last_status
.kind () == TARGET_WAITKIND_THREAD_EXITED
)
4611 /* We're reporting this thread as stopped. Update its
4612 "want-stopped" state to what the client wants, until it
4613 gets a new resume action. */
4614 current_thread
->last_resume_kind
= resume_stop
;
4615 current_thread
->last_status
= cs
.last_status
;
4620 if (!target_running ())
4622 /* The last process exited. We're done. */
4626 if (cs
.last_status
.kind () == TARGET_WAITKIND_EXITED
4627 || cs
.last_status
.kind () == TARGET_WAITKIND_SIGNALLED
4628 || cs
.last_status
.kind () == TARGET_WAITKIND_THREAD_EXITED
)
4632 /* A thread stopped with a signal, but gdb isn't
4633 connected to handle it. Pass it down to the
4634 inferior, as if it wasn't being traced. */
4635 enum gdb_signal signal
;
4637 threads_debug_printf ("GDB not connected; forwarding event %d for"
4639 (int) cs
.last_status
.kind (),
4640 target_pid_to_str (cs
.last_ptid
).c_str ());
4642 if (cs
.last_status
.kind () == TARGET_WAITKIND_STOPPED
)
4643 signal
= cs
.last_status
.sig ();
4645 signal
= GDB_SIGNAL_0
;
4646 target_continue (cs
.last_ptid
, signal
);
4650 push_stop_notification (cs
.last_ptid
, cs
.last_status
);
4653 /* Be sure to not change the selected thread behind GDB's back.
4654 Important in the non-stop mode asynchronous protocol. */
4655 set_desired_thread ();
4658 /* See gdbsupport/event-loop.h. */
4661 invoke_async_signal_handlers ()
4666 /* See gdbsupport/event-loop.h. */
4669 check_async_event_handlers ()
4674 /* See gdbsupport/errors.h */
4683 /* See gdbsupport/gdb_select.h. */
4686 gdb_select (int n
, fd_set
*readfds
, fd_set
*writefds
,
4687 fd_set
*exceptfds
, struct timeval
*timeout
)
4689 return select (n
, readfds
, writefds
, exceptfds
, timeout
);
4700 } // namespace selftests
4701 #endif /* GDB_SELF_TEST */