1 /* Main code for remote server for GDB.
2 Copyright (C) 1989-2020 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"
53 #define require_running_or_return(BUF) \
54 if (!target_running ()) \
60 #define require_running_or_break(BUF) \
61 if (!target_running ()) \
67 /* String containing the current directory (what getwd would return). */
69 char *current_directory
;
71 /* The environment to pass to the inferior when creating it. */
73 static gdb_environ our_environ
;
77 static bool extended_protocol
;
78 static bool response_needed
;
79 static bool exit_requested
;
81 /* --once: Exit after the first connection has closed. */
84 /* Whether to report TARGET_WAITKIND_NO_RESUMED events. */
85 static bool report_no_resumed
;
87 /* The event loop checks this to decide whether to continue accepting
89 static bool keep_processing_events
= true;
94 /* Set the PROGRAM_PATH. Here we adjust the path of the provided
96 void set (gdb::unique_xmalloc_ptr
<char> &&path
)
98 m_path
= std::move (path
);
100 /* Make sure we're using the absolute path of the inferior when
102 if (!contains_dir_separator (m_path
.get ()))
106 /* Check if the file is in our CWD. If it is, then we prefix
107 its name with CURRENT_DIRECTORY. Otherwise, we leave the
108 name as-is because we'll try searching for it in $PATH. */
109 if (is_regular_file (m_path
.get (), ®_file_errno
))
110 m_path
= gdb_abspath (m_path
.get ());
114 /* Return the PROGRAM_PATH. */
116 { return m_path
.get (); }
119 /* The program name, adjusted if needed. */
120 gdb::unique_xmalloc_ptr
<char> m_path
;
122 static std::vector
<char *> program_args
;
123 static std::string wrapper_argv
;
125 /* The PID of the originally created or attached inferior. Used to
126 send signals to the process when GDB sends us an asynchronous interrupt
127 (user hitting Control-C in the client), and to wait for the child to exit
128 when no longer debugging it. */
130 unsigned long signal_pid
;
132 /* Set if you want to disable optional thread related packets support
133 in gdbserver, for the sake of testing GDB against stubs that don't
135 bool disable_packet_vCont
;
136 bool disable_packet_Tthread
;
137 bool disable_packet_qC
;
138 bool disable_packet_qfThreadInfo
;
139 bool disable_packet_T
;
141 static unsigned char *mem_buf
;
143 /* A sub-class of 'struct notif_event' for stop, holding information
144 relative to a single stop reply. We keep a queue of these to
145 push to GDB in non-stop mode. */
147 struct vstop_notif
: public notif_event
149 /* Thread or process that got the event. */
153 struct target_waitstatus status
;
156 /* The current btrace configuration. This is gdbserver's mirror of GDB's
157 btrace configuration. */
158 static struct btrace_config current_btrace_conf
;
160 /* The client remote protocol state. */
162 static client_state g_client_state
;
167 client_state
&cs
= g_client_state
;
172 /* Put a stop reply to the stop reply queue. */
175 queue_stop_reply (ptid_t ptid
, struct target_waitstatus
*status
)
177 struct vstop_notif
*new_notif
= new struct vstop_notif
;
179 new_notif
->ptid
= ptid
;
180 new_notif
->status
= *status
;
182 notif_event_enque (¬if_stop
, new_notif
);
186 remove_all_on_match_ptid (struct notif_event
*event
, ptid_t filter_ptid
)
188 struct vstop_notif
*vstop_event
= (struct vstop_notif
*) event
;
190 return vstop_event
->ptid
.matches (filter_ptid
);
196 discard_queued_stop_replies (ptid_t ptid
)
198 std::list
<notif_event
*>::iterator iter
, next
, end
;
199 end
= notif_stop
.queue
.end ();
200 for (iter
= notif_stop
.queue
.begin (); iter
!= end
; iter
= next
)
205 if (remove_all_on_match_ptid (*iter
, ptid
))
208 notif_stop
.queue
.erase (iter
);
214 vstop_notif_reply (struct notif_event
*event
, char *own_buf
)
216 struct vstop_notif
*vstop
= (struct vstop_notif
*) event
;
218 prepare_resume_reply (own_buf
, vstop
->ptid
, &vstop
->status
);
221 /* Helper for in_queued_stop_replies. */
224 in_queued_stop_replies_ptid (struct notif_event
*event
, ptid_t filter_ptid
)
226 struct vstop_notif
*vstop_event
= (struct vstop_notif
*) event
;
228 if (vstop_event
->ptid
.matches (filter_ptid
))
231 /* Don't resume fork children that GDB does not know about yet. */
232 if ((vstop_event
->status
.kind
== TARGET_WAITKIND_FORKED
233 || vstop_event
->status
.kind
== TARGET_WAITKIND_VFORKED
)
234 && vstop_event
->status
.value
.related_pid
.matches (filter_ptid
))
243 in_queued_stop_replies (ptid_t ptid
)
245 for (notif_event
*event
: notif_stop
.queue
)
247 if (in_queued_stop_replies_ptid (event
, ptid
))
254 struct notif_server notif_stop
=
256 "vStopped", "Stop", {}, vstop_notif_reply
,
260 target_running (void)
262 return get_first_thread () != NULL
;
265 /* See gdbsupport/common-inferior.h. */
270 return !wrapper_argv
.empty () ? wrapper_argv
.c_str () : NULL
;
273 /* See gdbsupport/common-inferior.h. */
276 get_exec_file (int err
)
278 if (err
&& program_path
.get () == NULL
)
279 error (_("No executable file specified."));
281 return program_path
.get ();
293 attach_inferior (int pid
)
295 client_state
&cs
= get_client_state ();
296 /* myattach should return -1 if attaching is unsupported,
297 0 if it succeeded, and call error() otherwise. */
299 if (find_process_pid (pid
) != nullptr)
300 error ("Already attached to process %d\n", pid
);
302 if (myattach (pid
) != 0)
305 fprintf (stderr
, "Attached; pid = %d\n", pid
);
308 /* FIXME - It may be that we should get the SIGNAL_PID from the
309 attach function, so that it can be the main thread instead of
310 whichever we were told to attach to. */
315 cs
.last_ptid
= mywait (ptid_t (pid
), &cs
.last_status
, 0, 0);
317 /* GDB knows to ignore the first SIGSTOP after attaching to a running
318 process using the "attach" command, but this is different; it's
319 just using "target remote". Pretend it's just starting up. */
320 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
321 && cs
.last_status
.value
.sig
== GDB_SIGNAL_STOP
)
322 cs
.last_status
.value
.sig
= GDB_SIGNAL_TRAP
;
324 current_thread
->last_resume_kind
= resume_stop
;
325 current_thread
->last_status
= cs
.last_status
;
331 /* Decode a qXfer read request. Return 0 if everything looks OK,
335 decode_xfer_read (char *buf
, CORE_ADDR
*ofs
, unsigned int *len
)
337 /* After the read marker and annex, qXfer looks like a
338 traditional 'm' packet. */
339 decode_m_packet (buf
, ofs
, len
);
345 decode_xfer (char *buf
, char **object
, char **rw
, char **annex
, char **offset
)
347 /* Extract and NUL-terminate the object. */
349 while (*buf
&& *buf
!= ':')
355 /* Extract and NUL-terminate the read/write action. */
357 while (*buf
&& *buf
!= ':')
363 /* Extract and NUL-terminate the annex. */
365 while (*buf
&& *buf
!= ':')
375 /* Write the response to a successful qXfer read. Returns the
376 length of the (binary) data stored in BUF, corresponding
377 to as much of DATA/LEN as we could fit. IS_MORE controls
378 the first character of the response. */
380 write_qxfer_response (char *buf
, const gdb_byte
*data
, int len
, int is_more
)
389 return remote_escape_output (data
, len
, 1, (unsigned char *) buf
+ 1,
390 &out_len
, PBUFSIZ
- 2) + 1;
393 /* Handle btrace enabling in BTS format. */
396 handle_btrace_enable_bts (struct thread_info
*thread
)
398 if (thread
->btrace
!= NULL
)
399 error (_("Btrace already enabled."));
401 current_btrace_conf
.format
= BTRACE_FORMAT_BTS
;
402 thread
->btrace
= target_enable_btrace (thread
->id
, ¤t_btrace_conf
);
405 /* Handle btrace enabling in Intel Processor Trace format. */
408 handle_btrace_enable_pt (struct thread_info
*thread
)
410 if (thread
->btrace
!= NULL
)
411 error (_("Btrace already enabled."));
413 current_btrace_conf
.format
= BTRACE_FORMAT_PT
;
414 thread
->btrace
= target_enable_btrace (thread
->id
, ¤t_btrace_conf
);
417 /* Handle btrace disabling. */
420 handle_btrace_disable (struct thread_info
*thread
)
423 if (thread
->btrace
== NULL
)
424 error (_("Branch tracing not enabled."));
426 if (target_disable_btrace (thread
->btrace
) != 0)
427 error (_("Could not disable branch tracing."));
429 thread
->btrace
= NULL
;
432 /* Handle the "Qbtrace" packet. */
435 handle_btrace_general_set (char *own_buf
)
437 client_state
&cs
= get_client_state ();
438 struct thread_info
*thread
;
441 if (!startswith (own_buf
, "Qbtrace:"))
444 op
= own_buf
+ strlen ("Qbtrace:");
446 if (cs
.general_thread
== null_ptid
447 || cs
.general_thread
== minus_one_ptid
)
449 strcpy (own_buf
, "E.Must select a single thread.");
453 thread
= find_thread_ptid (cs
.general_thread
);
456 strcpy (own_buf
, "E.No such thread.");
462 if (strcmp (op
, "bts") == 0)
463 handle_btrace_enable_bts (thread
);
464 else if (strcmp (op
, "pt") == 0)
465 handle_btrace_enable_pt (thread
);
466 else if (strcmp (op
, "off") == 0)
467 handle_btrace_disable (thread
);
469 error (_("Bad Qbtrace operation. Use bts, pt, or off."));
473 catch (const gdb_exception_error
&exception
)
475 sprintf (own_buf
, "E.%s", exception
.what ());
481 /* Handle the "Qbtrace-conf" packet. */
484 handle_btrace_conf_general_set (char *own_buf
)
486 client_state
&cs
= get_client_state ();
487 struct thread_info
*thread
;
490 if (!startswith (own_buf
, "Qbtrace-conf:"))
493 op
= own_buf
+ strlen ("Qbtrace-conf:");
495 if (cs
.general_thread
== null_ptid
496 || cs
.general_thread
== minus_one_ptid
)
498 strcpy (own_buf
, "E.Must select a single thread.");
502 thread
= find_thread_ptid (cs
.general_thread
);
505 strcpy (own_buf
, "E.No such thread.");
509 if (startswith (op
, "bts:size="))
515 size
= strtoul (op
+ strlen ("bts:size="), &endp
, 16);
516 if (endp
== NULL
|| *endp
!= 0 || errno
!= 0 || size
> UINT_MAX
)
518 strcpy (own_buf
, "E.Bad size value.");
522 current_btrace_conf
.bts
.size
= (unsigned int) size
;
524 else if (strncmp (op
, "pt:size=", strlen ("pt:size=")) == 0)
530 size
= strtoul (op
+ strlen ("pt:size="), &endp
, 16);
531 if (endp
== NULL
|| *endp
!= 0 || errno
!= 0 || size
> UINT_MAX
)
533 strcpy (own_buf
, "E.Bad size value.");
537 current_btrace_conf
.pt
.size
= (unsigned int) size
;
541 strcpy (own_buf
, "E.Bad Qbtrace configuration option.");
549 /* Handle all of the extended 'Q' packets. */
552 handle_general_set (char *own_buf
)
554 client_state
&cs
= get_client_state ();
555 if (startswith (own_buf
, "QPassSignals:"))
557 int numsigs
= (int) GDB_SIGNAL_LAST
, i
;
558 const char *p
= own_buf
+ strlen ("QPassSignals:");
561 p
= decode_address_to_semicolon (&cursig
, p
);
562 for (i
= 0; i
< numsigs
; i
++)
566 cs
.pass_signals
[i
] = 1;
568 /* Keep looping, to clear the remaining signals. */
571 p
= decode_address_to_semicolon (&cursig
, p
);
574 cs
.pass_signals
[i
] = 0;
576 strcpy (own_buf
, "OK");
580 if (startswith (own_buf
, "QProgramSignals:"))
582 int numsigs
= (int) GDB_SIGNAL_LAST
, i
;
583 const char *p
= own_buf
+ strlen ("QProgramSignals:");
586 cs
.program_signals_p
= 1;
588 p
= decode_address_to_semicolon (&cursig
, p
);
589 for (i
= 0; i
< numsigs
; i
++)
593 cs
.program_signals
[i
] = 1;
595 /* Keep looping, to clear the remaining signals. */
598 p
= decode_address_to_semicolon (&cursig
, p
);
601 cs
.program_signals
[i
] = 0;
603 strcpy (own_buf
, "OK");
607 if (startswith (own_buf
, "QCatchSyscalls:"))
609 const char *p
= own_buf
+ sizeof ("QCatchSyscalls:") - 1;
612 struct process_info
*process
;
614 if (!target_running () || !target_supports_catch_syscall ())
620 if (strcmp (p
, "0") == 0)
622 else if (p
[0] == '1' && (p
[1] == ';' || p
[1] == '\0'))
626 fprintf (stderr
, "Unknown catch-syscalls mode requested: %s\n",
632 process
= current_process ();
633 process
->syscalls_to_catch
.clear ();
643 p
= decode_address_to_semicolon (&sysno
, p
);
644 process
->syscalls_to_catch
.push_back (sysno
);
648 process
->syscalls_to_catch
.push_back (ANY_SYSCALL
);
655 if (strcmp (own_buf
, "QEnvironmentReset") == 0)
657 our_environ
= gdb_environ::from_host_environ ();
663 if (startswith (own_buf
, "QEnvironmentHexEncoded:"))
665 const char *p
= own_buf
+ sizeof ("QEnvironmentHexEncoded:") - 1;
666 /* The final form of the environment variable. FINAL_VAR will
667 hold the 'VAR=VALUE' format. */
668 std::string final_var
= hex2str (p
);
669 std::string var_name
, var_value
;
673 debug_printf (_("[QEnvironmentHexEncoded received '%s']\n"), p
);
674 debug_printf (_("[Environment variable to be set: '%s']\n"),
679 size_t pos
= final_var
.find ('=');
680 if (pos
== std::string::npos
)
682 warning (_("Unexpected format for environment variable: '%s'"),
688 var_name
= final_var
.substr (0, pos
);
689 var_value
= final_var
.substr (pos
+ 1, std::string::npos
);
691 our_environ
.set (var_name
.c_str (), var_value
.c_str ());
697 if (startswith (own_buf
, "QEnvironmentUnset:"))
699 const char *p
= own_buf
+ sizeof ("QEnvironmentUnset:") - 1;
700 std::string varname
= hex2str (p
);
704 debug_printf (_("[QEnvironmentUnset received '%s']\n"), p
);
705 debug_printf (_("[Environment variable to be unset: '%s']\n"),
710 our_environ
.unset (varname
.c_str ());
716 if (strcmp (own_buf
, "QStartNoAckMode") == 0)
720 debug_printf ("[noack mode enabled]\n");
729 if (startswith (own_buf
, "QNonStop:"))
731 char *mode
= own_buf
+ 9;
735 if (strcmp (mode
, "0") == 0)
737 else if (strcmp (mode
, "1") == 0)
741 /* We don't know what this mode is, so complain to
743 fprintf (stderr
, "Unknown non-stop mode requested: %s\n",
749 req_str
= req
? "non-stop" : "all-stop";
750 if (the_target
->start_non_stop (req
== 1) != 0)
752 fprintf (stderr
, "Setting %s mode failed\n", req_str
);
757 non_stop
= (req
!= 0);
760 debug_printf ("[%s mode enabled]\n", req_str
);
766 if (startswith (own_buf
, "QDisableRandomization:"))
768 char *packet
= own_buf
+ strlen ("QDisableRandomization:");
771 unpack_varlen_hex (packet
, &setting
);
772 cs
.disable_randomization
= setting
;
776 debug_printf (cs
.disable_randomization
777 ? "[address space randomization disabled]\n"
778 : "[address space randomization enabled]\n");
785 if (target_supports_tracepoints ()
786 && handle_tracepoint_general_set (own_buf
))
789 if (startswith (own_buf
, "QAgent:"))
791 char *mode
= own_buf
+ strlen ("QAgent:");
794 if (strcmp (mode
, "0") == 0)
796 else if (strcmp (mode
, "1") == 0)
800 /* We don't know what this value is, so complain to GDB. */
801 sprintf (own_buf
, "E.Unknown QAgent value");
805 /* Update the flag. */
808 debug_printf ("[%s agent]\n", req
? "Enable" : "Disable");
813 if (handle_btrace_general_set (own_buf
))
816 if (handle_btrace_conf_general_set (own_buf
))
819 if (startswith (own_buf
, "QThreadEvents:"))
821 char *mode
= own_buf
+ strlen ("QThreadEvents:");
822 enum tribool req
= TRIBOOL_UNKNOWN
;
824 if (strcmp (mode
, "0") == 0)
826 else if (strcmp (mode
, "1") == 0)
830 /* We don't know what this mode is, so complain to GDB. */
831 sprintf (own_buf
, "E.Unknown thread-events mode requested: %s\n",
836 cs
.report_thread_events
= (req
== TRIBOOL_TRUE
);
840 const char *req_str
= cs
.report_thread_events
? "enabled" : "disabled";
842 debug_printf ("[thread events are now %s]\n", req_str
);
849 if (startswith (own_buf
, "QStartupWithShell:"))
851 const char *value
= own_buf
+ strlen ("QStartupWithShell:");
853 if (strcmp (value
, "1") == 0)
854 startup_with_shell
= true;
855 else if (strcmp (value
, "0") == 0)
856 startup_with_shell
= false;
860 fprintf (stderr
, "Unknown value to startup-with-shell: %s\n",
867 debug_printf (_("[Inferior will %s started with shell]"),
868 startup_with_shell
? "be" : "not be");
874 if (startswith (own_buf
, "QSetWorkingDir:"))
876 const char *p
= own_buf
+ strlen ("QSetWorkingDir:");
880 std::string path
= hex2str (p
);
882 set_inferior_cwd (path
.c_str ());
885 debug_printf (_("[Set the inferior's current directory to %s]\n"),
890 /* An empty argument means that we should clear out any
891 previously set cwd for the inferior. */
892 set_inferior_cwd (NULL
);
896 [Unset the inferior's current directory; will use gdbserver's cwd]\n"));
903 /* Otherwise we didn't know what packet it was. Say we didn't
909 get_features_xml (const char *annex
)
911 const struct target_desc
*desc
= current_target_desc ();
913 /* `desc->xmltarget' defines what to return when looking for the
914 "target.xml" file. Its contents can either be verbatim XML code
915 (prefixed with a '@') or else the name of the actual XML file to
916 be used in place of "target.xml".
918 This variable is set up from the auto-generated
919 init_registers_... routine for the current target. */
921 if (strcmp (annex
, "target.xml") == 0)
923 const char *ret
= tdesc_get_features_xml (desc
);
935 /* Look for the annex. */
936 for (i
= 0; xml_builtin
[i
][0] != NULL
; i
++)
937 if (strcmp (annex
, xml_builtin
[i
][0]) == 0)
940 if (xml_builtin
[i
][0] != NULL
)
941 return xml_builtin
[i
][1];
949 monitor_show_help (void)
951 monitor_output ("The following monitor commands are supported:\n");
952 monitor_output (" set debug <0|1>\n");
953 monitor_output (" Enable general debugging messages\n");
954 monitor_output (" set debug-hw-points <0|1>\n");
955 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
956 monitor_output (" set remote-debug <0|1>\n");
957 monitor_output (" Enable remote protocol debugging messages\n");
958 monitor_output (" set debug-format option1[,option2,...]\n");
959 monitor_output (" Add additional information to debugging messages\n");
960 monitor_output (" Options: all, none");
961 monitor_output (", timestamp");
962 monitor_output ("\n");
963 monitor_output (" exit\n");
964 monitor_output (" Quit GDBserver\n");
967 /* Read trace frame or inferior memory. Returns the number of bytes
968 actually read, zero when no further transfer is possible, and -1 on
969 error. Return of a positive value smaller than LEN does not
970 indicate there's no more to be read, only the end of the transfer.
971 E.g., when GDB reads memory from a traceframe, a first request may
972 be served from a memory block that does not cover the whole request
973 length. A following request gets the rest served from either
974 another block (of the same traceframe) or from the read-only
978 gdb_read_memory (CORE_ADDR memaddr
, unsigned char *myaddr
, int len
)
980 client_state
&cs
= get_client_state ();
983 if (cs
.current_traceframe
>= 0)
986 ULONGEST length
= len
;
988 if (traceframe_read_mem (cs
.current_traceframe
,
989 memaddr
, myaddr
, len
, &nbytes
))
991 /* Data read from trace buffer, we're done. */
994 if (!in_readonly_region (memaddr
, length
))
996 /* Otherwise we have a valid readonly case, fall through. */
997 /* (assume no half-trace half-real blocks for now) */
1000 res
= prepare_to_access_memory ();
1003 if (set_desired_thread ())
1004 res
= read_inferior_memory (memaddr
, myaddr
, len
);
1007 done_accessing_memory ();
1009 return res
== 0 ? len
: -1;
1015 /* Write trace frame or inferior memory. Actually, writing to trace
1016 frames is forbidden. */
1019 gdb_write_memory (CORE_ADDR memaddr
, const unsigned char *myaddr
, int len
)
1021 client_state
&cs
= get_client_state ();
1022 if (cs
.current_traceframe
>= 0)
1028 ret
= prepare_to_access_memory ();
1031 if (set_desired_thread ())
1032 ret
= target_write_memory (memaddr
, myaddr
, len
);
1035 done_accessing_memory ();
1041 /* Subroutine of handle_search_memory to simplify it. */
1044 handle_search_memory_1 (CORE_ADDR start_addr
, CORE_ADDR search_space_len
,
1045 gdb_byte
*pattern
, unsigned pattern_len
,
1046 gdb_byte
*search_buf
,
1047 unsigned chunk_size
, unsigned search_buf_size
,
1048 CORE_ADDR
*found_addrp
)
1050 /* Prime the search buffer. */
1052 if (gdb_read_memory (start_addr
, search_buf
, search_buf_size
)
1055 warning ("Unable to access %ld bytes of target "
1056 "memory at 0x%lx, halting search.",
1057 (long) search_buf_size
, (long) start_addr
);
1061 /* Perform the search.
1063 The loop is kept simple by allocating [N + pattern-length - 1] bytes.
1064 When we've scanned N bytes we copy the trailing bytes to the start and
1065 read in another N bytes. */
1067 while (search_space_len
>= pattern_len
)
1069 gdb_byte
*found_ptr
;
1070 unsigned nr_search_bytes
= (search_space_len
< search_buf_size
1074 found_ptr
= (gdb_byte
*) memmem (search_buf
, nr_search_bytes
, pattern
,
1077 if (found_ptr
!= NULL
)
1079 CORE_ADDR found_addr
= start_addr
+ (found_ptr
- search_buf
);
1080 *found_addrp
= found_addr
;
1084 /* Not found in this chunk, skip to next chunk. */
1086 /* Don't let search_space_len wrap here, it's unsigned. */
1087 if (search_space_len
>= chunk_size
)
1088 search_space_len
-= chunk_size
;
1090 search_space_len
= 0;
1092 if (search_space_len
>= pattern_len
)
1094 unsigned keep_len
= search_buf_size
- chunk_size
;
1095 CORE_ADDR read_addr
= start_addr
+ chunk_size
+ keep_len
;
1098 /* Copy the trailing part of the previous iteration to the front
1099 of the buffer for the next iteration. */
1100 memcpy (search_buf
, search_buf
+ chunk_size
, keep_len
);
1102 nr_to_read
= (search_space_len
- keep_len
< chunk_size
1103 ? search_space_len
- keep_len
1106 if (gdb_read_memory (read_addr
, search_buf
+ keep_len
,
1107 nr_to_read
) != nr_to_read
)
1109 warning ("Unable to access %ld bytes of target memory "
1110 "at 0x%lx, halting search.",
1111 (long) nr_to_read
, (long) read_addr
);
1115 start_addr
+= chunk_size
;
1124 /* Handle qSearch:memory packets. */
1127 handle_search_memory (char *own_buf
, int packet_len
)
1129 CORE_ADDR start_addr
;
1130 CORE_ADDR search_space_len
;
1132 unsigned int pattern_len
;
1133 /* NOTE: also defined in find.c testcase. */
1134 #define SEARCH_CHUNK_SIZE 16000
1135 const unsigned chunk_size
= SEARCH_CHUNK_SIZE
;
1136 /* Buffer to hold memory contents for searching. */
1137 gdb_byte
*search_buf
;
1138 unsigned search_buf_size
;
1140 CORE_ADDR found_addr
;
1141 int cmd_name_len
= sizeof ("qSearch:memory:") - 1;
1143 pattern
= (gdb_byte
*) malloc (packet_len
);
1144 if (pattern
== NULL
)
1146 error ("Unable to allocate memory to perform the search");
1147 strcpy (own_buf
, "E00");
1150 if (decode_search_memory_packet (own_buf
+ cmd_name_len
,
1151 packet_len
- cmd_name_len
,
1152 &start_addr
, &search_space_len
,
1153 pattern
, &pattern_len
) < 0)
1156 error ("Error in parsing qSearch:memory packet");
1157 strcpy (own_buf
, "E00");
1161 search_buf_size
= chunk_size
+ pattern_len
- 1;
1163 /* No point in trying to allocate a buffer larger than the search space. */
1164 if (search_space_len
< search_buf_size
)
1165 search_buf_size
= search_space_len
;
1167 search_buf
= (gdb_byte
*) malloc (search_buf_size
);
1168 if (search_buf
== NULL
)
1171 error ("Unable to allocate memory to perform the search");
1172 strcpy (own_buf
, "E00");
1176 found
= handle_search_memory_1 (start_addr
, search_space_len
,
1177 pattern
, pattern_len
,
1178 search_buf
, chunk_size
, search_buf_size
,
1182 sprintf (own_buf
, "1,%lx", (long) found_addr
);
1183 else if (found
== 0)
1184 strcpy (own_buf
, "0");
1186 strcpy (own_buf
, "E00");
1192 /* Handle the "D" packet. */
1195 handle_detach (char *own_buf
)
1197 client_state
&cs
= get_client_state ();
1199 process_info
*process
;
1201 if (cs
.multi_process
)
1204 int pid
= strtol (&own_buf
[2], NULL
, 16);
1206 process
= find_process_pid (pid
);
1210 process
= (current_thread
!= nullptr
1211 ? get_thread_process (current_thread
)
1215 if (process
== NULL
)
1217 write_enn (own_buf
);
1221 if ((tracing
&& disconnected_tracing
) || any_persistent_commands (process
))
1223 if (tracing
&& disconnected_tracing
)
1225 "Disconnected tracing in effect, "
1226 "leaving gdbserver attached to the process\n");
1228 if (any_persistent_commands (process
))
1230 "Persistent commands are present, "
1231 "leaving gdbserver attached to the process\n");
1233 /* Make sure we're in non-stop/async mode, so we we can both
1234 wait for an async socket accept, and handle async target
1235 events simultaneously. There's also no point either in
1236 having the target stop all threads, when we're going to
1237 pass signals down without informing GDB. */
1241 debug_printf ("Forcing non-stop mode\n");
1244 the_target
->start_non_stop (true);
1247 process
->gdb_detached
= 1;
1249 /* Detaching implicitly resumes all threads. */
1250 target_continue_no_signal (minus_one_ptid
);
1256 fprintf (stderr
, "Detaching from process %d\n", process
->pid
);
1259 /* We'll need this after PROCESS has been destroyed. */
1260 int pid
= process
->pid
;
1262 if (detach_inferior (process
) != 0)
1263 write_enn (own_buf
);
1266 discard_queued_stop_replies (ptid_t (pid
));
1269 if (extended_protocol
|| target_running ())
1271 /* There is still at least one inferior remaining or
1272 we are in extended mode, so don't terminate gdbserver,
1273 and instead treat this like a normal program exit. */
1274 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
1275 cs
.last_status
.value
.integer
= 0;
1276 cs
.last_ptid
= ptid_t (pid
);
1278 current_thread
= NULL
;
1285 /* If we are attached, then we can exit. Otherwise, we
1286 need to hang around doing nothing, until the child is
1288 join_inferior (pid
);
1294 /* Parse options to --debug-format= and "monitor set debug-format".
1295 ARG is the text after "--debug-format=" or "monitor set debug-format".
1296 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1297 This triggers calls to monitor_output.
1298 The result is an empty string if all options were parsed ok, otherwise an
1299 error message which the caller must free.
1301 N.B. These commands affect all debug format settings, they are not
1302 cumulative. If a format is not specified, it is turned off.
1303 However, we don't go to extra trouble with things like
1304 "monitor set debug-format all,none,timestamp".
1305 Instead we just parse them one at a time, in order.
1307 The syntax for "monitor set debug" we support here is not identical
1308 to gdb's "set debug foo on|off" because we also use this function to
1309 parse "--debug-format=foo,bar". */
1312 parse_debug_format_options (const char *arg
, int is_monitor
)
1314 /* First turn all debug format options off. */
1315 debug_timestamp
= 0;
1317 /* First remove leading spaces, for "monitor set debug-format". */
1318 while (isspace (*arg
))
1321 std::vector
<gdb::unique_xmalloc_ptr
<char>> options
1322 = delim_string_to_char_ptr_vec (arg
, ',');
1324 for (const gdb::unique_xmalloc_ptr
<char> &option
: options
)
1326 if (strcmp (option
.get (), "all") == 0)
1328 debug_timestamp
= 1;
1330 monitor_output ("All extra debug format options enabled.\n");
1332 else if (strcmp (option
.get (), "none") == 0)
1334 debug_timestamp
= 0;
1336 monitor_output ("All extra debug format options disabled.\n");
1338 else if (strcmp (option
.get (), "timestamp") == 0)
1340 debug_timestamp
= 1;
1342 monitor_output ("Timestamps will be added to debug output.\n");
1344 else if (*option
== '\0')
1346 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1350 return string_printf ("Unknown debug-format argument: \"%s\"\n",
1354 return std::string ();
1357 /* Handle monitor commands not handled by target-specific handlers. */
1360 handle_monitor_command (char *mon
, char *own_buf
)
1362 if (strcmp (mon
, "set debug 1") == 0)
1365 monitor_output ("Debug output enabled.\n");
1367 else if (strcmp (mon
, "set debug 0") == 0)
1370 monitor_output ("Debug output disabled.\n");
1372 else if (strcmp (mon
, "set debug-hw-points 1") == 0)
1374 show_debug_regs
= 1;
1375 monitor_output ("H/W point debugging output enabled.\n");
1377 else if (strcmp (mon
, "set debug-hw-points 0") == 0)
1379 show_debug_regs
= 0;
1380 monitor_output ("H/W point debugging output disabled.\n");
1382 else if (strcmp (mon
, "set remote-debug 1") == 0)
1385 monitor_output ("Protocol debug output enabled.\n");
1387 else if (strcmp (mon
, "set remote-debug 0") == 0)
1390 monitor_output ("Protocol debug output disabled.\n");
1392 else if (startswith (mon
, "set debug-format "))
1394 std::string error_msg
1395 = parse_debug_format_options (mon
+ sizeof ("set debug-format ") - 1,
1398 if (!error_msg
.empty ())
1400 monitor_output (error_msg
.c_str ());
1401 monitor_show_help ();
1402 write_enn (own_buf
);
1405 else if (strcmp (mon
, "set debug-file") == 0)
1406 debug_set_output (nullptr);
1407 else if (startswith (mon
, "set debug-file "))
1408 debug_set_output (mon
+ sizeof ("set debug-file ") - 1);
1409 else if (strcmp (mon
, "help") == 0)
1410 monitor_show_help ();
1411 else if (strcmp (mon
, "exit") == 0)
1412 exit_requested
= true;
1415 monitor_output ("Unknown monitor command.\n\n");
1416 monitor_show_help ();
1417 write_enn (own_buf
);
1421 /* Associates a callback with each supported qXfer'able object. */
1425 /* The object this handler handles. */
1428 /* Request that the target transfer up to LEN 8-bit bytes of the
1429 target's OBJECT. The OFFSET, for a seekable object, specifies
1430 the starting point. The ANNEX can be used to provide additional
1431 data-specific information to the target.
1433 Return the number of bytes actually transfered, zero when no
1434 further transfer is possible, -1 on error, -2 when the transfer
1435 is not supported, and -3 on a verbose error message that should
1436 be preserved. Return of a positive value smaller than LEN does
1437 not indicate the end of the object, only the end of the transfer.
1439 One, and only one, of readbuf or writebuf must be non-NULL. */
1440 int (*xfer
) (const char *annex
,
1441 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1442 ULONGEST offset
, LONGEST len
);
1445 /* Handle qXfer:auxv:read. */
1448 handle_qxfer_auxv (const char *annex
,
1449 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1450 ULONGEST offset
, LONGEST len
)
1452 if (!the_target
->supports_read_auxv () || writebuf
!= NULL
)
1455 if (annex
[0] != '\0' || current_thread
== NULL
)
1458 return the_target
->read_auxv (offset
, readbuf
, len
);
1461 /* Handle qXfer:exec-file:read. */
1464 handle_qxfer_exec_file (const char *annex
,
1465 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1466 ULONGEST offset
, LONGEST len
)
1472 if (!the_target
->supports_pid_to_exec_file () || writebuf
!= NULL
)
1475 if (annex
[0] == '\0')
1477 if (current_thread
== NULL
)
1480 pid
= pid_of (current_thread
);
1484 annex
= unpack_varlen_hex (annex
, &pid
);
1485 if (annex
[0] != '\0')
1492 file
= the_target
->pid_to_exec_file (pid
);
1496 total_len
= strlen (file
);
1498 if (offset
> total_len
)
1501 if (offset
+ len
> total_len
)
1502 len
= total_len
- offset
;
1504 memcpy (readbuf
, file
+ offset
, len
);
1508 /* Handle qXfer:features:read. */
1511 handle_qxfer_features (const char *annex
,
1512 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1513 ULONGEST offset
, LONGEST len
)
1515 const char *document
;
1518 if (writebuf
!= NULL
)
1521 if (!target_running ())
1524 /* Grab the correct annex. */
1525 document
= get_features_xml (annex
);
1526 if (document
== NULL
)
1529 total_len
= strlen (document
);
1531 if (offset
> total_len
)
1534 if (offset
+ len
> total_len
)
1535 len
= total_len
- offset
;
1537 memcpy (readbuf
, document
+ offset
, len
);
1541 /* Handle qXfer:libraries:read. */
1544 handle_qxfer_libraries (const char *annex
,
1545 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1546 ULONGEST offset
, LONGEST len
)
1548 if (writebuf
!= NULL
)
1551 if (annex
[0] != '\0' || current_thread
== NULL
)
1554 std::string document
= "<library-list version=\"1.0\">\n";
1556 for (const dll_info
&dll
: all_dlls
)
1557 document
+= string_printf
1558 (" <library name=\"%s\"><segment address=\"0x%s\"/></library>\n",
1559 dll
.name
.c_str (), paddress (dll
.base_addr
));
1561 document
+= "</library-list>\n";
1563 if (offset
> document
.length ())
1566 if (offset
+ len
> document
.length ())
1567 len
= document
.length () - offset
;
1569 memcpy (readbuf
, &document
[offset
], len
);
1574 /* Handle qXfer:libraries-svr4:read. */
1577 handle_qxfer_libraries_svr4 (const char *annex
,
1578 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1579 ULONGEST offset
, LONGEST len
)
1581 if (writebuf
!= NULL
)
1584 if (current_thread
== NULL
1585 || !the_target
->supports_qxfer_libraries_svr4 ())
1588 return the_target
->qxfer_libraries_svr4 (annex
, readbuf
, writebuf
,
1592 /* Handle qXfer:osadata:read. */
1595 handle_qxfer_osdata (const char *annex
,
1596 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1597 ULONGEST offset
, LONGEST len
)
1599 if (!the_target
->supports_qxfer_osdata () || writebuf
!= NULL
)
1602 return the_target
->qxfer_osdata (annex
, readbuf
, NULL
, offset
, len
);
1605 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1608 handle_qxfer_siginfo (const char *annex
,
1609 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1610 ULONGEST offset
, LONGEST len
)
1612 if (!the_target
->supports_qxfer_siginfo ())
1615 if (annex
[0] != '\0' || current_thread
== NULL
)
1618 return the_target
->qxfer_siginfo (annex
, readbuf
, writebuf
, offset
, len
);
1621 /* Handle qXfer:statictrace:read. */
1624 handle_qxfer_statictrace (const char *annex
,
1625 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1626 ULONGEST offset
, LONGEST len
)
1628 client_state
&cs
= get_client_state ();
1631 if (writebuf
!= NULL
)
1634 if (annex
[0] != '\0' || current_thread
== NULL
1635 || cs
.current_traceframe
== -1)
1638 if (traceframe_read_sdata (cs
.current_traceframe
, offset
,
1639 readbuf
, len
, &nbytes
))
1644 /* Helper for handle_qxfer_threads_proper.
1645 Emit the XML to describe the thread of INF. */
1648 handle_qxfer_threads_worker (thread_info
*thread
, struct buffer
*buffer
)
1650 ptid_t ptid
= ptid_of (thread
);
1652 int core
= target_core_of_thread (ptid
);
1654 const char *name
= target_thread_name (ptid
);
1657 bool handle_status
= target_thread_handle (ptid
, &handle
, &handle_len
);
1659 write_ptid (ptid_s
, ptid
);
1661 buffer_xml_printf (buffer
, "<thread id=\"%s\"", ptid_s
);
1665 sprintf (core_s
, "%d", core
);
1666 buffer_xml_printf (buffer
, " core=\"%s\"", core_s
);
1670 buffer_xml_printf (buffer
, " name=\"%s\"", name
);
1674 char *handle_s
= (char *) alloca (handle_len
* 2 + 1);
1675 bin2hex (handle
, handle_s
, handle_len
);
1676 buffer_xml_printf (buffer
, " handle=\"%s\"", handle_s
);
1679 buffer_xml_printf (buffer
, "/>\n");
1682 /* Helper for handle_qxfer_threads. Return true on success, false
1686 handle_qxfer_threads_proper (struct buffer
*buffer
)
1688 client_state
&cs
= get_client_state ();
1690 scoped_restore save_current_thread
1691 = make_scoped_restore (¤t_thread
);
1692 scoped_restore save_current_general_thread
1693 = make_scoped_restore (&cs
.general_thread
);
1695 buffer_grow_str (buffer
, "<threads>\n");
1697 process_info
*error_proc
= find_process ([&] (process_info
*process
)
1699 /* The target may need to access memory and registers (e.g. via
1700 libthread_db) to fetch thread properties. Prepare for memory
1701 access here, so that we potentially pause threads just once
1702 for all accesses. Note that even if someday we stop needing
1703 to pause threads to access memory, we will need to be able to
1704 access registers, or other ptrace accesses like
1705 PTRACE_GET_THREAD_AREA. */
1707 /* Need to switch to each process in turn, because
1708 prepare_to_access_memory prepares for an access in the
1709 current process pointed to by general_thread. */
1710 switch_to_process (process
);
1711 cs
.general_thread
= current_thread
->id
;
1713 int res
= prepare_to_access_memory ();
1716 for_each_thread (process
->pid
, [&] (thread_info
*thread
)
1718 handle_qxfer_threads_worker (thread
, buffer
);
1721 done_accessing_memory ();
1728 buffer_grow_str0 (buffer
, "</threads>\n");
1729 return error_proc
== nullptr;
1732 /* Handle qXfer:threads:read. */
1735 handle_qxfer_threads (const char *annex
,
1736 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1737 ULONGEST offset
, LONGEST len
)
1739 static char *result
= 0;
1740 static unsigned int result_length
= 0;
1742 if (writebuf
!= NULL
)
1745 if (annex
[0] != '\0')
1750 struct buffer buffer
;
1751 /* When asked for data at offset 0, generate everything and store into
1752 'result'. Successive reads will be served off 'result'. */
1756 buffer_init (&buffer
);
1758 bool res
= handle_qxfer_threads_proper (&buffer
);
1760 result
= buffer_finish (&buffer
);
1761 result_length
= strlen (result
);
1762 buffer_free (&buffer
);
1768 if (offset
>= result_length
)
1770 /* We're out of data. */
1777 if (len
> result_length
- offset
)
1778 len
= result_length
- offset
;
1780 memcpy (readbuf
, result
+ offset
, len
);
1785 /* Handle qXfer:traceframe-info:read. */
1788 handle_qxfer_traceframe_info (const char *annex
,
1789 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1790 ULONGEST offset
, LONGEST len
)
1792 client_state
&cs
= get_client_state ();
1793 static char *result
= 0;
1794 static unsigned int result_length
= 0;
1796 if (writebuf
!= NULL
)
1799 if (!target_running () || annex
[0] != '\0' || cs
.current_traceframe
== -1)
1804 struct buffer buffer
;
1806 /* When asked for data at offset 0, generate everything and
1807 store into 'result'. Successive reads will be served off
1811 buffer_init (&buffer
);
1813 traceframe_read_info (cs
.current_traceframe
, &buffer
);
1815 result
= buffer_finish (&buffer
);
1816 result_length
= strlen (result
);
1817 buffer_free (&buffer
);
1820 if (offset
>= result_length
)
1822 /* We're out of data. */
1829 if (len
> result_length
- offset
)
1830 len
= result_length
- offset
;
1832 memcpy (readbuf
, result
+ offset
, len
);
1836 /* Handle qXfer:fdpic:read. */
1839 handle_qxfer_fdpic (const char *annex
, gdb_byte
*readbuf
,
1840 const gdb_byte
*writebuf
, ULONGEST offset
, LONGEST len
)
1842 if (!the_target
->supports_read_loadmap ())
1845 if (current_thread
== NULL
)
1848 return the_target
->read_loadmap (annex
, offset
, readbuf
, len
);
1851 /* Handle qXfer:btrace:read. */
1854 handle_qxfer_btrace (const char *annex
,
1855 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1856 ULONGEST offset
, LONGEST len
)
1858 client_state
&cs
= get_client_state ();
1859 static struct buffer cache
;
1860 struct thread_info
*thread
;
1861 enum btrace_read_type type
;
1864 if (writebuf
!= NULL
)
1867 if (cs
.general_thread
== null_ptid
1868 || cs
.general_thread
== minus_one_ptid
)
1870 strcpy (cs
.own_buf
, "E.Must select a single thread.");
1874 thread
= find_thread_ptid (cs
.general_thread
);
1877 strcpy (cs
.own_buf
, "E.No such thread.");
1881 if (thread
->btrace
== NULL
)
1883 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
1887 if (strcmp (annex
, "all") == 0)
1888 type
= BTRACE_READ_ALL
;
1889 else if (strcmp (annex
, "new") == 0)
1890 type
= BTRACE_READ_NEW
;
1891 else if (strcmp (annex
, "delta") == 0)
1892 type
= BTRACE_READ_DELTA
;
1895 strcpy (cs
.own_buf
, "E.Bad annex.");
1901 buffer_free (&cache
);
1905 result
= target_read_btrace (thread
->btrace
, &cache
, type
);
1907 memcpy (cs
.own_buf
, cache
.buffer
, cache
.used_size
);
1909 catch (const gdb_exception_error
&exception
)
1911 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
1918 else if (offset
> cache
.used_size
)
1920 buffer_free (&cache
);
1924 if (len
> cache
.used_size
- offset
)
1925 len
= cache
.used_size
- offset
;
1927 memcpy (readbuf
, cache
.buffer
+ offset
, len
);
1932 /* Handle qXfer:btrace-conf:read. */
1935 handle_qxfer_btrace_conf (const char *annex
,
1936 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1937 ULONGEST offset
, LONGEST len
)
1939 client_state
&cs
= get_client_state ();
1940 static struct buffer cache
;
1941 struct thread_info
*thread
;
1944 if (writebuf
!= NULL
)
1947 if (annex
[0] != '\0')
1950 if (cs
.general_thread
== null_ptid
1951 || cs
.general_thread
== minus_one_ptid
)
1953 strcpy (cs
.own_buf
, "E.Must select a single thread.");
1957 thread
= find_thread_ptid (cs
.general_thread
);
1960 strcpy (cs
.own_buf
, "E.No such thread.");
1964 if (thread
->btrace
== NULL
)
1966 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
1972 buffer_free (&cache
);
1976 result
= target_read_btrace_conf (thread
->btrace
, &cache
);
1978 memcpy (cs
.own_buf
, cache
.buffer
, cache
.used_size
);
1980 catch (const gdb_exception_error
&exception
)
1982 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
1989 else if (offset
> cache
.used_size
)
1991 buffer_free (&cache
);
1995 if (len
> cache
.used_size
- offset
)
1996 len
= cache
.used_size
- offset
;
1998 memcpy (readbuf
, cache
.buffer
+ offset
, len
);
2003 static const struct qxfer qxfer_packets
[] =
2005 { "auxv", handle_qxfer_auxv
},
2006 { "btrace", handle_qxfer_btrace
},
2007 { "btrace-conf", handle_qxfer_btrace_conf
},
2008 { "exec-file", handle_qxfer_exec_file
},
2009 { "fdpic", handle_qxfer_fdpic
},
2010 { "features", handle_qxfer_features
},
2011 { "libraries", handle_qxfer_libraries
},
2012 { "libraries-svr4", handle_qxfer_libraries_svr4
},
2013 { "osdata", handle_qxfer_osdata
},
2014 { "siginfo", handle_qxfer_siginfo
},
2015 { "statictrace", handle_qxfer_statictrace
},
2016 { "threads", handle_qxfer_threads
},
2017 { "traceframe-info", handle_qxfer_traceframe_info
},
2021 handle_qxfer (char *own_buf
, int packet_len
, int *new_packet_len_p
)
2029 if (!startswith (own_buf
, "qXfer:"))
2032 /* Grab the object, r/w and annex. */
2033 if (decode_xfer (own_buf
+ 6, &object
, &rw
, &annex
, &offset
) < 0)
2035 write_enn (own_buf
);
2040 i
< sizeof (qxfer_packets
) / sizeof (qxfer_packets
[0]);
2043 const struct qxfer
*q
= &qxfer_packets
[i
];
2045 if (strcmp (object
, q
->object
) == 0)
2047 if (strcmp (rw
, "read") == 0)
2049 unsigned char *data
;
2054 /* Grab the offset and length. */
2055 if (decode_xfer_read (offset
, &ofs
, &len
) < 0)
2057 write_enn (own_buf
);
2061 /* Read one extra byte, as an indicator of whether there is
2063 if (len
> PBUFSIZ
- 2)
2065 data
= (unsigned char *) malloc (len
+ 1);
2068 write_enn (own_buf
);
2071 n
= (*q
->xfer
) (annex
, data
, NULL
, ofs
, len
+ 1);
2079 /* Preserve error message. */
2082 write_enn (own_buf
);
2084 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, len
, 1);
2086 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, n
, 0);
2091 else if (strcmp (rw
, "write") == 0)
2096 unsigned char *data
;
2098 strcpy (own_buf
, "E00");
2099 data
= (unsigned char *) malloc (packet_len
- (offset
- own_buf
));
2102 write_enn (own_buf
);
2105 if (decode_xfer_write (offset
, packet_len
- (offset
- own_buf
),
2106 &ofs
, &len
, data
) < 0)
2109 write_enn (own_buf
);
2113 n
= (*q
->xfer
) (annex
, NULL
, data
, ofs
, len
);
2121 /* Preserve error message. */
2124 write_enn (own_buf
);
2126 sprintf (own_buf
, "%x", n
);
2139 /* Compute 32 bit CRC from inferior memory.
2141 On success, return 32 bit CRC.
2142 On failure, return (unsigned long long) -1. */
2144 static unsigned long long
2145 crc32 (CORE_ADDR base
, int len
, unsigned int crc
)
2149 unsigned char byte
= 0;
2151 /* Return failure if memory read fails. */
2152 if (read_inferior_memory (base
, &byte
, 1) != 0)
2153 return (unsigned long long) -1;
2155 crc
= xcrc32 (&byte
, 1, crc
);
2158 return (unsigned long long) crc
;
2161 /* Add supported btrace packets to BUF. */
2164 supported_btrace_packets (char *buf
)
2166 strcat (buf
, ";Qbtrace:bts+");
2167 strcat (buf
, ";Qbtrace-conf:bts:size+");
2168 strcat (buf
, ";Qbtrace:pt+");
2169 strcat (buf
, ";Qbtrace-conf:pt:size+");
2170 strcat (buf
, ";Qbtrace:off+");
2171 strcat (buf
, ";qXfer:btrace:read+");
2172 strcat (buf
, ";qXfer:btrace-conf:read+");
2175 /* Handle all of the extended 'q' packets. */
2178 handle_query (char *own_buf
, int packet_len
, int *new_packet_len_p
)
2180 client_state
&cs
= get_client_state ();
2181 static std::list
<thread_info
*>::const_iterator thread_iter
;
2183 /* Reply the current thread id. */
2184 if (strcmp ("qC", own_buf
) == 0 && !disable_packet_qC
)
2187 require_running_or_return (own_buf
);
2189 if (cs
.general_thread
!= null_ptid
&& cs
.general_thread
!= minus_one_ptid
)
2190 ptid
= cs
.general_thread
;
2193 thread_iter
= all_threads
.begin ();
2194 ptid
= (*thread_iter
)->id
;
2197 sprintf (own_buf
, "QC");
2199 write_ptid (own_buf
, ptid
);
2203 if (strcmp ("qSymbol::", own_buf
) == 0)
2205 struct thread_info
*save_thread
= current_thread
;
2207 /* For qSymbol, GDB only changes the current thread if the
2208 previous current thread was of a different process. So if
2209 the previous thread is gone, we need to pick another one of
2210 the same process. This can happen e.g., if we followed an
2211 exec in a non-leader thread. */
2212 if (current_thread
== NULL
)
2215 = find_any_thread_of_pid (cs
.general_thread
.pid ());
2217 /* Just in case, if we didn't find a thread, then bail out
2218 instead of crashing. */
2219 if (current_thread
== NULL
)
2221 write_enn (own_buf
);
2222 current_thread
= save_thread
;
2227 /* GDB is suggesting new symbols have been loaded. This may
2228 mean a new shared library has been detected as loaded, so
2229 take the opportunity to check if breakpoints we think are
2230 inserted, still are. Note that it isn't guaranteed that
2231 we'll see this when a shared library is loaded, and nor will
2232 we see this for unloads (although breakpoints in unloaded
2233 libraries shouldn't trigger), as GDB may not find symbols for
2234 the library at all. We also re-validate breakpoints when we
2235 see a second GDB breakpoint for the same address, and or when
2236 we access breakpoint shadows. */
2237 validate_breakpoints ();
2239 if (target_supports_tracepoints ())
2240 tracepoint_look_up_symbols ();
2242 if (current_thread
!= NULL
)
2243 the_target
->look_up_symbols ();
2245 current_thread
= save_thread
;
2247 strcpy (own_buf
, "OK");
2251 if (!disable_packet_qfThreadInfo
)
2253 if (strcmp ("qfThreadInfo", own_buf
) == 0)
2255 require_running_or_return (own_buf
);
2256 thread_iter
= all_threads
.begin ();
2259 ptid_t ptid
= (*thread_iter
)->id
;
2260 write_ptid (own_buf
, ptid
);
2265 if (strcmp ("qsThreadInfo", own_buf
) == 0)
2267 require_running_or_return (own_buf
);
2268 if (thread_iter
!= all_threads
.end ())
2271 ptid_t ptid
= (*thread_iter
)->id
;
2272 write_ptid (own_buf
, ptid
);
2278 sprintf (own_buf
, "l");
2284 if (the_target
->supports_read_offsets ()
2285 && strcmp ("qOffsets", own_buf
) == 0)
2287 CORE_ADDR text
, data
;
2289 require_running_or_return (own_buf
);
2290 if (the_target
->read_offsets (&text
, &data
))
2291 sprintf (own_buf
, "Text=%lX;Data=%lX;Bss=%lX",
2292 (long)text
, (long)data
, (long)data
);
2294 write_enn (own_buf
);
2299 /* Protocol features query. */
2300 if (startswith (own_buf
, "qSupported")
2301 && (own_buf
[10] == ':' || own_buf
[10] == '\0'))
2303 char *p
= &own_buf
[10];
2304 int gdb_supports_qRelocInsn
= 0;
2306 /* Process each feature being provided by GDB. The first
2307 feature will follow a ':', and latter features will follow
2311 std::vector
<std::string
> qsupported
;
2312 std::vector
<const char *> unknowns
;
2314 /* Two passes, to avoid nested strtok calls in
2315 target_process_qsupported. */
2317 for (p
= strtok_r (p
+ 1, ";", &saveptr
);
2319 p
= strtok_r (NULL
, ";", &saveptr
))
2320 qsupported
.emplace_back (p
);
2322 for (const std::string
&feature
: qsupported
)
2324 if (feature
== "multiprocess+")
2326 /* GDB supports and wants multi-process support if
2328 if (target_supports_multi_process ())
2329 cs
.multi_process
= 1;
2331 else if (feature
== "qRelocInsn+")
2333 /* GDB supports relocate instruction requests. */
2334 gdb_supports_qRelocInsn
= 1;
2336 else if (feature
== "swbreak+")
2338 /* GDB wants us to report whether a trap is caused
2339 by a software breakpoint and for us to handle PC
2340 adjustment if necessary on this target. */
2341 if (target_supports_stopped_by_sw_breakpoint ())
2342 cs
.swbreak_feature
= 1;
2344 else if (feature
== "hwbreak+")
2346 /* GDB wants us to report whether a trap is caused
2347 by a hardware breakpoint. */
2348 if (target_supports_stopped_by_hw_breakpoint ())
2349 cs
.hwbreak_feature
= 1;
2351 else if (feature
== "fork-events+")
2353 /* GDB supports and wants fork events if possible. */
2354 if (target_supports_fork_events ())
2355 cs
.report_fork_events
= 1;
2357 else if (feature
== "vfork-events+")
2359 /* GDB supports and wants vfork events if possible. */
2360 if (target_supports_vfork_events ())
2361 cs
.report_vfork_events
= 1;
2363 else if (feature
== "exec-events+")
2365 /* GDB supports and wants exec events if possible. */
2366 if (target_supports_exec_events ())
2367 cs
.report_exec_events
= 1;
2369 else if (feature
== "vContSupported+")
2370 cs
.vCont_supported
= 1;
2371 else if (feature
== "QThreadEvents+")
2373 else if (feature
== "no-resumed+")
2375 /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
2377 report_no_resumed
= true;
2381 /* Move the unknown features all together. */
2382 unknowns
.push_back (feature
.c_str ());
2386 /* Give the target backend a chance to process the unknown
2388 target_process_qsupported (unknowns
);
2392 "PacketSize=%x;QPassSignals+;QProgramSignals+;"
2393 "QStartupWithShell+;QEnvironmentHexEncoded+;"
2394 "QEnvironmentReset+;QEnvironmentUnset+;"
2398 if (target_supports_catch_syscall ())
2399 strcat (own_buf
, ";QCatchSyscalls+");
2401 if (the_target
->supports_qxfer_libraries_svr4 ())
2402 strcat (own_buf
, ";qXfer:libraries-svr4:read+"
2403 ";augmented-libraries-svr4-read+");
2406 /* We do not have any hook to indicate whether the non-SVR4 target
2407 backend supports qXfer:libraries:read, so always report it. */
2408 strcat (own_buf
, ";qXfer:libraries:read+");
2411 if (the_target
->supports_read_auxv ())
2412 strcat (own_buf
, ";qXfer:auxv:read+");
2414 if (the_target
->supports_qxfer_siginfo ())
2415 strcat (own_buf
, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2417 if (the_target
->supports_read_loadmap ())
2418 strcat (own_buf
, ";qXfer:fdpic:read+");
2420 /* We always report qXfer:features:read, as targets may
2421 install XML files on a subsequent call to arch_setup.
2422 If we reported to GDB on startup that we don't support
2423 qXfer:feature:read at all, we will never be re-queried. */
2424 strcat (own_buf
, ";qXfer:features:read+");
2426 if (cs
.transport_is_reliable
)
2427 strcat (own_buf
, ";QStartNoAckMode+");
2429 if (the_target
->supports_qxfer_osdata ())
2430 strcat (own_buf
, ";qXfer:osdata:read+");
2432 if (target_supports_multi_process ())
2433 strcat (own_buf
, ";multiprocess+");
2435 if (target_supports_fork_events ())
2436 strcat (own_buf
, ";fork-events+");
2438 if (target_supports_vfork_events ())
2439 strcat (own_buf
, ";vfork-events+");
2441 if (target_supports_exec_events ())
2442 strcat (own_buf
, ";exec-events+");
2444 if (target_supports_non_stop ())
2445 strcat (own_buf
, ";QNonStop+");
2447 if (target_supports_disable_randomization ())
2448 strcat (own_buf
, ";QDisableRandomization+");
2450 strcat (own_buf
, ";qXfer:threads:read+");
2452 if (target_supports_tracepoints ())
2454 strcat (own_buf
, ";ConditionalTracepoints+");
2455 strcat (own_buf
, ";TraceStateVariables+");
2456 strcat (own_buf
, ";TracepointSource+");
2457 strcat (own_buf
, ";DisconnectedTracing+");
2458 if (gdb_supports_qRelocInsn
&& target_supports_fast_tracepoints ())
2459 strcat (own_buf
, ";FastTracepoints+");
2460 strcat (own_buf
, ";StaticTracepoints+");
2461 strcat (own_buf
, ";InstallInTrace+");
2462 strcat (own_buf
, ";qXfer:statictrace:read+");
2463 strcat (own_buf
, ";qXfer:traceframe-info:read+");
2464 strcat (own_buf
, ";EnableDisableTracepoints+");
2465 strcat (own_buf
, ";QTBuffer:size+");
2466 strcat (own_buf
, ";tracenz+");
2469 if (target_supports_hardware_single_step ()
2470 || target_supports_software_single_step () )
2472 strcat (own_buf
, ";ConditionalBreakpoints+");
2474 strcat (own_buf
, ";BreakpointCommands+");
2476 if (target_supports_agent ())
2477 strcat (own_buf
, ";QAgent+");
2479 supported_btrace_packets (own_buf
);
2481 if (target_supports_stopped_by_sw_breakpoint ())
2482 strcat (own_buf
, ";swbreak+");
2484 if (target_supports_stopped_by_hw_breakpoint ())
2485 strcat (own_buf
, ";hwbreak+");
2487 if (the_target
->supports_pid_to_exec_file ())
2488 strcat (own_buf
, ";qXfer:exec-file:read+");
2490 strcat (own_buf
, ";vContSupported+");
2492 strcat (own_buf
, ";QThreadEvents+");
2494 strcat (own_buf
, ";no-resumed+");
2496 /* Reinitialize components as needed for the new connection. */
2497 hostio_handle_new_gdb_connection ();
2498 target_handle_new_gdb_connection ();
2503 /* Thread-local storage support. */
2504 if (the_target
->supports_get_tls_address ()
2505 && startswith (own_buf
, "qGetTLSAddr:"))
2507 char *p
= own_buf
+ 12;
2508 CORE_ADDR parts
[2], address
= 0;
2510 ptid_t ptid
= null_ptid
;
2512 require_running_or_return (own_buf
);
2514 for (i
= 0; i
< 3; i
++)
2522 p2
= strchr (p
, ',');
2535 ptid
= read_ptid (p
, NULL
);
2537 decode_address (&parts
[i
- 1], p
, len
);
2541 if (p
!= NULL
|| i
< 3)
2545 struct thread_info
*thread
= find_thread_ptid (ptid
);
2550 err
= the_target
->get_tls_address (thread
, parts
[0], parts
[1],
2556 strcpy (own_buf
, paddress(address
));
2561 write_enn (own_buf
);
2565 /* Otherwise, pretend we do not understand this packet. */
2568 /* Windows OS Thread Information Block address support. */
2569 if (the_target
->supports_get_tib_address ()
2570 && startswith (own_buf
, "qGetTIBAddr:"))
2575 ptid_t ptid
= read_ptid (own_buf
+ 12, &annex
);
2577 n
= the_target
->get_tib_address (ptid
, &tlb
);
2580 strcpy (own_buf
, paddress(tlb
));
2585 write_enn (own_buf
);
2591 /* Handle "monitor" commands. */
2592 if (startswith (own_buf
, "qRcmd,"))
2594 char *mon
= (char *) malloc (PBUFSIZ
);
2595 int len
= strlen (own_buf
+ 6);
2599 write_enn (own_buf
);
2604 || hex2bin (own_buf
+ 6, (gdb_byte
*) mon
, len
/ 2) != len
/ 2)
2606 write_enn (own_buf
);
2610 mon
[len
/ 2] = '\0';
2614 if (the_target
->handle_monitor_command (mon
) == 0)
2615 /* Default processing. */
2616 handle_monitor_command (mon
, own_buf
);
2622 if (startswith (own_buf
, "qSearch:memory:"))
2624 require_running_or_return (own_buf
);
2625 handle_search_memory (own_buf
, packet_len
);
2629 if (strcmp (own_buf
, "qAttached") == 0
2630 || startswith (own_buf
, "qAttached:"))
2632 struct process_info
*process
;
2634 if (own_buf
[sizeof ("qAttached") - 1])
2636 int pid
= strtoul (own_buf
+ sizeof ("qAttached:") - 1, NULL
, 16);
2637 process
= find_process_pid (pid
);
2641 require_running_or_return (own_buf
);
2642 process
= current_process ();
2645 if (process
== NULL
)
2647 write_enn (own_buf
);
2651 strcpy (own_buf
, process
->attached
? "1" : "0");
2655 if (startswith (own_buf
, "qCRC:"))
2657 /* CRC check (compare-section). */
2661 unsigned long long crc
;
2663 require_running_or_return (own_buf
);
2664 comma
= unpack_varlen_hex (own_buf
+ 5, &base
);
2665 if (*comma
++ != ',')
2667 write_enn (own_buf
);
2670 len
= strtoul (comma
, NULL
, 16);
2671 crc
= crc32 (base
, len
, 0xffffffff);
2672 /* Check for memory failure. */
2673 if (crc
== (unsigned long long) -1)
2675 write_enn (own_buf
);
2678 sprintf (own_buf
, "C%lx", (unsigned long) crc
);
2682 if (handle_qxfer (own_buf
, packet_len
, new_packet_len_p
))
2685 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf
))
2688 /* Otherwise we didn't know what packet it was. Say we didn't
2693 static void gdb_wants_all_threads_stopped (void);
2694 static void resume (struct thread_resume
*actions
, size_t n
);
2696 /* The callback that is passed to visit_actioned_threads. */
2697 typedef int (visit_actioned_threads_callback_ftype
)
2698 (const struct thread_resume
*, struct thread_info
*);
2700 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
2701 true if CALLBACK returns true. Returns false if no matching thread
2702 is found or CALLBACK results false.
2703 Note: This function is itself a callback for find_thread. */
2706 visit_actioned_threads (thread_info
*thread
,
2707 const struct thread_resume
*actions
,
2709 visit_actioned_threads_callback_ftype
*callback
)
2711 for (size_t i
= 0; i
< num_actions
; i
++)
2713 const struct thread_resume
*action
= &actions
[i
];
2715 if (action
->thread
== minus_one_ptid
2716 || action
->thread
== thread
->id
2717 || ((action
->thread
.pid ()
2718 == thread
->id
.pid ())
2719 && action
->thread
.lwp () == -1))
2721 if ((*callback
) (action
, thread
))
2729 /* Callback for visit_actioned_threads. If the thread has a pending
2730 status to report, report it now. */
2733 handle_pending_status (const struct thread_resume
*resumption
,
2734 struct thread_info
*thread
)
2736 client_state
&cs
= get_client_state ();
2737 if (thread
->status_pending_p
)
2739 thread
->status_pending_p
= 0;
2741 cs
.last_status
= thread
->last_status
;
2742 cs
.last_ptid
= thread
->id
;
2743 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, &cs
.last_status
);
2749 /* Parse vCont packets. */
2751 handle_v_cont (char *own_buf
)
2755 struct thread_resume
*resume_info
;
2756 struct thread_resume default_action
{ null_ptid
};
2758 /* Count the number of semicolons in the packet. There should be one
2759 for every action. */
2765 p
= strchr (p
, ';');
2768 resume_info
= (struct thread_resume
*) malloc (n
* sizeof (resume_info
[0]));
2769 if (resume_info
== NULL
)
2777 memset (&resume_info
[i
], 0, sizeof resume_info
[i
]);
2779 if (p
[0] == 's' || p
[0] == 'S')
2780 resume_info
[i
].kind
= resume_step
;
2781 else if (p
[0] == 'r')
2782 resume_info
[i
].kind
= resume_step
;
2783 else if (p
[0] == 'c' || p
[0] == 'C')
2784 resume_info
[i
].kind
= resume_continue
;
2785 else if (p
[0] == 't')
2786 resume_info
[i
].kind
= resume_stop
;
2790 if (p
[0] == 'S' || p
[0] == 'C')
2793 int sig
= strtol (p
+ 1, &q
, 16);
2798 if (!gdb_signal_to_host_p ((enum gdb_signal
) sig
))
2800 resume_info
[i
].sig
= gdb_signal_to_host ((enum gdb_signal
) sig
);
2802 else if (p
[0] == 'r')
2806 p
= unpack_varlen_hex (p
+ 1, &addr
);
2807 resume_info
[i
].step_range_start
= addr
;
2812 p
= unpack_varlen_hex (p
+ 1, &addr
);
2813 resume_info
[i
].step_range_end
= addr
;
2822 resume_info
[i
].thread
= minus_one_ptid
;
2823 default_action
= resume_info
[i
];
2825 /* Note: we don't increment i here, we'll overwrite this entry
2826 the next time through. */
2828 else if (p
[0] == ':')
2831 ptid_t ptid
= read_ptid (p
+ 1, &q
);
2836 if (p
[0] != ';' && p
[0] != 0)
2839 resume_info
[i
].thread
= ptid
;
2846 resume_info
[i
] = default_action
;
2848 resume (resume_info
, n
);
2853 write_enn (own_buf
);
2858 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
2861 resume (struct thread_resume
*actions
, size_t num_actions
)
2863 client_state
&cs
= get_client_state ();
2866 /* Check if among the threads that GDB wants actioned, there's
2867 one with a pending status to report. If so, skip actually
2868 resuming/stopping and report the pending event
2871 thread_info
*thread_with_status
= find_thread ([&] (thread_info
*thread
)
2873 return visit_actioned_threads (thread
, actions
, num_actions
,
2874 handle_pending_status
);
2877 if (thread_with_status
!= NULL
)
2883 the_target
->resume (actions
, num_actions
);
2886 write_ok (cs
.own_buf
);
2889 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
, 0, 1);
2891 if (cs
.last_status
.kind
== TARGET_WAITKIND_NO_RESUMED
2892 && !report_no_resumed
)
2894 /* The client does not support this stop reply. At least
2896 sprintf (cs
.own_buf
, "E.No unwaited-for children left.");
2897 disable_async_io ();
2901 if (cs
.last_status
.kind
!= TARGET_WAITKIND_EXITED
2902 && cs
.last_status
.kind
!= TARGET_WAITKIND_SIGNALLED
2903 && cs
.last_status
.kind
!= TARGET_WAITKIND_NO_RESUMED
)
2904 current_thread
->last_status
= cs
.last_status
;
2906 /* From the client's perspective, all-stop mode always stops all
2907 threads implicitly (and the target backend has already done
2908 so by now). Tag all threads as "want-stopped", so we don't
2909 resume them implicitly without the client telling us to. */
2910 gdb_wants_all_threads_stopped ();
2911 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, &cs
.last_status
);
2912 disable_async_io ();
2914 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
2915 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
2916 target_mourn_inferior (cs
.last_ptid
);
2920 /* Attach to a new program. Return 1 if successful, 0 if failure. */
2922 handle_v_attach (char *own_buf
)
2924 client_state
&cs
= get_client_state ();
2927 pid
= strtol (own_buf
+ 8, NULL
, 16);
2928 if (pid
!= 0 && attach_inferior (pid
) == 0)
2930 /* Don't report shared library events after attaching, even if
2931 some libraries are preloaded. GDB will always poll the
2932 library list. Avoids the "stopped by shared library event"
2933 notice on the GDB side. */
2938 /* In non-stop, we don't send a resume reply. Stop events
2939 will follow up using the normal notification
2944 prepare_resume_reply (own_buf
, cs
.last_ptid
, &cs
.last_status
);
2950 write_enn (own_buf
);
2955 /* Run a new program. Return 1 if successful, 0 if failure. */
2957 handle_v_run (char *own_buf
)
2959 client_state
&cs
= get_client_state ();
2961 std::vector
<char *> new_argv
;
2962 char *new_program_name
= NULL
;
2966 for (p
= own_buf
+ strlen ("vRun;"); p
&& *p
; p
= strchr (p
, ';'))
2972 for (i
= 0, p
= own_buf
+ strlen ("vRun;"); *p
; p
= next_p
, ++i
)
2974 next_p
= strchr (p
, ';');
2976 next_p
= p
+ strlen (p
);
2978 if (i
== 0 && p
== next_p
)
2980 /* No program specified. */
2981 new_program_name
= NULL
;
2983 else if (p
== next_p
)
2985 /* Empty argument. */
2986 new_argv
.push_back (xstrdup (""));
2990 size_t len
= (next_p
- p
) / 2;
2991 /* ARG is the unquoted argument received via the RSP. */
2992 char *arg
= (char *) xmalloc (len
+ 1);
2993 /* FULL_ARGS will contain the quoted version of ARG. */
2994 char *full_arg
= (char *) xmalloc ((len
+ 1) * 2);
2995 /* These are pointers used to navigate the strings above. */
2996 char *tmp_arg
= arg
;
2997 char *tmp_full_arg
= full_arg
;
3000 hex2bin (p
, (gdb_byte
*) arg
, len
);
3003 while (*tmp_arg
!= '\0')
3009 *tmp_full_arg
= '\'';
3015 /* Quote single quote. */
3016 *tmp_full_arg
= '\\';
3024 *tmp_full_arg
= *tmp_arg
;
3030 *tmp_full_arg
++ = '\'';
3032 /* Finish FULL_ARG and push it into the vector containing
3034 *tmp_full_arg
= '\0';
3036 new_program_name
= full_arg
;
3038 new_argv
.push_back (full_arg
);
3045 if (new_program_name
== NULL
)
3047 /* GDB didn't specify a program to run. Use the program from the
3048 last run with the new argument list. */
3049 if (program_path
.get () == NULL
)
3051 write_enn (own_buf
);
3052 free_vector_argv (new_argv
);
3057 program_path
.set (gdb::unique_xmalloc_ptr
<char> (new_program_name
));
3059 /* Free the old argv and install the new one. */
3060 free_vector_argv (program_args
);
3061 program_args
= new_argv
;
3063 target_create_inferior (program_path
.get (), program_args
);
3065 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
3067 prepare_resume_reply (own_buf
, cs
.last_ptid
, &cs
.last_status
);
3069 /* In non-stop, sending a resume reply doesn't set the general
3070 thread, but GDB assumes a vRun sets it (this is so GDB can
3071 query which is the main thread of the new inferior. */
3073 cs
.general_thread
= cs
.last_ptid
;
3079 write_enn (own_buf
);
3084 /* Kill process. Return 1 if successful, 0 if failure. */
3086 handle_v_kill (char *own_buf
)
3088 client_state
&cs
= get_client_state ();
3090 char *p
= &own_buf
[6];
3091 if (cs
.multi_process
)
3092 pid
= strtol (p
, NULL
, 16);
3096 process_info
*proc
= find_process_pid (pid
);
3098 if (proc
!= nullptr && kill_inferior (proc
) == 0)
3100 cs
.last_status
.kind
= TARGET_WAITKIND_SIGNALLED
;
3101 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
3102 cs
.last_ptid
= ptid_t (pid
);
3103 discard_queued_stop_replies (cs
.last_ptid
);
3109 write_enn (own_buf
);
3114 /* Handle all of the extended 'v' packets. */
3116 handle_v_requests (char *own_buf
, int packet_len
, int *new_packet_len
)
3118 client_state
&cs
= get_client_state ();
3119 if (!disable_packet_vCont
)
3121 if (strcmp (own_buf
, "vCtrlC") == 0)
3123 the_target
->request_interrupt ();
3128 if (startswith (own_buf
, "vCont;"))
3130 handle_v_cont (own_buf
);
3134 if (startswith (own_buf
, "vCont?"))
3136 strcpy (own_buf
, "vCont;c;C;t");
3138 if (target_supports_hardware_single_step ()
3139 || target_supports_software_single_step ()
3140 || !cs
.vCont_supported
)
3142 /* If target supports single step either by hardware or by
3143 software, add actions s and S to the list of supported
3144 actions. On the other hand, if GDB doesn't request the
3145 supported vCont actions in qSupported packet, add s and
3146 S to the list too. */
3147 own_buf
= own_buf
+ strlen (own_buf
);
3148 strcpy (own_buf
, ";s;S");
3151 if (target_supports_range_stepping ())
3153 own_buf
= own_buf
+ strlen (own_buf
);
3154 strcpy (own_buf
, ";r");
3160 if (startswith (own_buf
, "vFile:")
3161 && handle_vFile (own_buf
, packet_len
, new_packet_len
))
3164 if (startswith (own_buf
, "vAttach;"))
3166 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3168 fprintf (stderr
, "Already debugging a process\n");
3169 write_enn (own_buf
);
3172 handle_v_attach (own_buf
);
3176 if (startswith (own_buf
, "vRun;"))
3178 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3180 fprintf (stderr
, "Already debugging a process\n");
3181 write_enn (own_buf
);
3184 handle_v_run (own_buf
);
3188 if (startswith (own_buf
, "vKill;"))
3190 if (!target_running ())
3192 fprintf (stderr
, "No process to kill\n");
3193 write_enn (own_buf
);
3196 handle_v_kill (own_buf
);
3200 if (handle_notif_ack (own_buf
, packet_len
))
3203 /* Otherwise we didn't know what packet it was. Say we didn't
3209 /* Resume thread and wait for another event. In non-stop mode,
3210 don't really wait here, but return immediatelly to the event
3213 myresume (char *own_buf
, int step
, int sig
)
3215 client_state
&cs
= get_client_state ();
3216 struct thread_resume resume_info
[2];
3218 int valid_cont_thread
;
3220 valid_cont_thread
= (cs
.cont_thread
!= null_ptid
3221 && cs
.cont_thread
!= minus_one_ptid
);
3223 if (step
|| sig
|| valid_cont_thread
)
3225 resume_info
[0].thread
= current_ptid
;
3227 resume_info
[0].kind
= resume_step
;
3229 resume_info
[0].kind
= resume_continue
;
3230 resume_info
[0].sig
= sig
;
3234 if (!valid_cont_thread
)
3236 resume_info
[n
].thread
= minus_one_ptid
;
3237 resume_info
[n
].kind
= resume_continue
;
3238 resume_info
[n
].sig
= 0;
3242 resume (resume_info
, n
);
3245 /* Callback for for_each_thread. Make a new stop reply for each
3249 queue_stop_reply_callback (thread_info
*thread
)
3251 /* For now, assume targets that don't have this callback also don't
3252 manage the thread's last_status field. */
3253 if (!the_target
->supports_thread_stopped ())
3255 struct vstop_notif
*new_notif
= new struct vstop_notif
;
3257 new_notif
->ptid
= thread
->id
;
3258 new_notif
->status
= thread
->last_status
;
3259 /* Pass the last stop reply back to GDB, but don't notify
3261 notif_event_enque (¬if_stop
, new_notif
);
3265 if (target_thread_stopped (thread
))
3269 std::string status_string
3270 = target_waitstatus_to_string (&thread
->last_status
);
3272 debug_printf ("Reporting thread %s as already stopped with %s\n",
3273 target_pid_to_str (thread
->id
),
3274 status_string
.c_str ());
3277 gdb_assert (thread
->last_status
.kind
!= TARGET_WAITKIND_IGNORE
);
3279 /* Pass the last stop reply back to GDB, but don't notify
3281 queue_stop_reply (thread
->id
, &thread
->last_status
);
3286 /* Set this inferior threads's state as "want-stopped". We won't
3287 resume this thread until the client gives us another action for
3291 gdb_wants_thread_stopped (thread_info
*thread
)
3293 thread
->last_resume_kind
= resume_stop
;
3295 if (thread
->last_status
.kind
== TARGET_WAITKIND_IGNORE
)
3297 /* Most threads are stopped implicitly (all-stop); tag that with
3299 thread
->last_status
.kind
= TARGET_WAITKIND_STOPPED
;
3300 thread
->last_status
.value
.sig
= GDB_SIGNAL_0
;
3304 /* Set all threads' states as "want-stopped". */
3307 gdb_wants_all_threads_stopped (void)
3309 for_each_thread (gdb_wants_thread_stopped
);
3312 /* Callback for for_each_thread. If the thread is stopped with an
3313 interesting event, mark it as having a pending event. */
3316 set_pending_status_callback (thread_info
*thread
)
3318 if (thread
->last_status
.kind
!= TARGET_WAITKIND_STOPPED
3319 || (thread
->last_status
.value
.sig
!= GDB_SIGNAL_0
3320 /* A breakpoint, watchpoint or finished step from a previous
3321 GDB run isn't considered interesting for a new GDB run.
3322 If we left those pending, the new GDB could consider them
3323 random SIGTRAPs. This leaves out real async traps. We'd
3324 have to peek into the (target-specific) siginfo to
3325 distinguish those. */
3326 && thread
->last_status
.value
.sig
!= GDB_SIGNAL_TRAP
))
3327 thread
->status_pending_p
= 1;
3330 /* Status handler for the '?' packet. */
3333 handle_status (char *own_buf
)
3335 client_state
&cs
= get_client_state ();
3337 /* GDB is connected, don't forward events to the target anymore. */
3338 for_each_process ([] (process_info
*process
) {
3339 process
->gdb_detached
= 0;
3342 /* In non-stop mode, we must send a stop reply for each stopped
3343 thread. In all-stop mode, just send one for the first stopped
3348 for_each_thread (queue_stop_reply_callback
);
3350 /* The first is sent immediatly. OK is sent if there is no
3351 stopped thread, which is the same handling of the vStopped
3352 packet (by design). */
3353 notif_write_event (¬if_stop
, cs
.own_buf
);
3357 thread_info
*thread
= NULL
;
3359 target_pause_all (false);
3360 target_stabilize_threads ();
3361 gdb_wants_all_threads_stopped ();
3363 /* We can only report one status, but we might be coming out of
3364 non-stop -- if more than one thread is stopped with
3365 interesting events, leave events for the threads we're not
3366 reporting now pending. They'll be reported the next time the
3367 threads are resumed. Start by marking all interesting events
3369 for_each_thread (set_pending_status_callback
);
3371 /* Prefer the last thread that reported an event to GDB (even if
3372 that was a GDB_SIGNAL_TRAP). */
3373 if (cs
.last_status
.kind
!= TARGET_WAITKIND_IGNORE
3374 && cs
.last_status
.kind
!= TARGET_WAITKIND_EXITED
3375 && cs
.last_status
.kind
!= TARGET_WAITKIND_SIGNALLED
)
3376 thread
= find_thread_ptid (cs
.last_ptid
);
3378 /* If the last event thread is not found for some reason, look
3379 for some other thread that might have an event to report. */
3381 thread
= find_thread ([] (thread_info
*thr_arg
)
3383 return thr_arg
->status_pending_p
;
3386 /* If we're still out of luck, simply pick the first thread in
3389 thread
= get_first_thread ();
3393 struct thread_info
*tp
= (struct thread_info
*) thread
;
3395 /* We're reporting this event, so it's no longer
3397 tp
->status_pending_p
= 0;
3399 /* GDB assumes the current thread is the thread we're
3400 reporting the status for. */
3401 cs
.general_thread
= thread
->id
;
3402 set_desired_thread ();
3404 gdb_assert (tp
->last_status
.kind
!= TARGET_WAITKIND_IGNORE
);
3405 prepare_resume_reply (own_buf
, tp
->id
, &tp
->last_status
);
3408 strcpy (own_buf
, "W00");
3413 gdbserver_version (void)
3415 printf ("GNU gdbserver %s%s\n"
3416 "Copyright (C) 2020 Free Software Foundation, Inc.\n"
3417 "gdbserver is free software, covered by the "
3418 "GNU General Public License.\n"
3419 "This gdbserver was configured as \"%s\"\n",
3420 PKGVERSION
, version
, host_name
);
3424 gdbserver_usage (FILE *stream
)
3426 fprintf (stream
, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3427 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3428 "\tgdbserver [OPTIONS] --multi COMM\n"
3430 "COMM may either be a tty device (for serial debugging),\n"
3431 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3432 "stdin/stdout of gdbserver.\n"
3433 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3434 "PID is the process ID to attach to, when --attach is specified.\n"
3436 "Operating modes:\n"
3438 " --attach Attach to running process PID.\n"
3439 " --multi Start server without a specific program, and\n"
3440 " only quit when explicitly commanded.\n"
3441 " --once Exit after the first connection has closed.\n"
3442 " --help Print this message and then exit.\n"
3443 " --version Display version information and exit.\n"
3447 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3448 " --disable-randomization\n"
3449 " Run PROG with address space randomization disabled.\n"
3450 " --no-disable-randomization\n"
3451 " Don't disable address space randomization when\n"
3453 " --startup-with-shell\n"
3454 " Start PROG using a shell. I.e., execs a shell that\n"
3455 " then execs PROG. (default)\n"
3456 " --no-startup-with-shell\n"
3457 " Exec PROG directly instead of using a shell.\n"
3458 " Disables argument globbing and variable substitution\n"
3459 " on UNIX-like systems.\n"
3463 " --debug Enable general debugging output.\n"
3464 " --debug-format=OPT1[,OPT2,...]\n"
3465 " Specify extra content in debugging output.\n"
3470 " --remote-debug Enable remote protocol debugging output.\n"
3471 " --disable-packet=OPT1[,OPT2,...]\n"
3472 " Disable support for RSP packets or features.\n"
3474 " vCont, Tthread, qC, qfThreadInfo and \n"
3475 " threads (disable all threading packets).\n"
3477 "For more information, consult the GDB manual (available as on-line \n"
3478 "info or a printed manual).\n");
3479 if (REPORT_BUGS_TO
[0] && stream
== stdout
)
3480 fprintf (stream
, "Report bugs to \"%s\".\n", REPORT_BUGS_TO
);
3484 gdbserver_show_disableable (FILE *stream
)
3486 fprintf (stream
, "Disableable packets:\n"
3487 " vCont \tAll vCont packets\n"
3488 " qC \tQuerying the current thread\n"
3489 " qfThreadInfo\tThread listing\n"
3490 " Tthread \tPassing the thread specifier in the "
3491 "T stop reply packet\n"
3492 " threads \tAll of the above\n");
3495 /* Start up the event loop. This is the entry point to the event
3501 /* Loop until there is nothing to do. This is the entry point to
3502 the event loop engine. If nothing is ready at this time, wait
3503 for something to happen (via wait_for_event), then process it.
3504 Return when there are no longer event sources to wait for. */
3506 keep_processing_events
= true;
3507 while (keep_processing_events
)
3509 /* Any events already waiting in the queue? */
3510 int res
= gdb_do_one_event ();
3512 /* Was there an error? */
3517 /* We are done with the event loop. There are no more event sources
3518 to listen to. So we exit gdbserver. */
3522 kill_inferior_callback (process_info
*process
)
3524 kill_inferior (process
);
3525 discard_queued_stop_replies (ptid_t (process
->pid
));
3528 /* Call this when exiting gdbserver with possible inferiors that need
3529 to be killed or detached from. */
3532 detach_or_kill_for_exit (void)
3534 /* First print a list of the inferiors we will be killing/detaching.
3535 This is to assist the user, for example, in case the inferior unexpectedly
3536 dies after we exit: did we screw up or did the inferior exit on its own?
3537 Having this info will save some head-scratching. */
3539 if (have_started_inferiors_p ())
3541 fprintf (stderr
, "Killing process(es):");
3543 for_each_process ([] (process_info
*process
) {
3544 if (!process
->attached
)
3545 fprintf (stderr
, " %d", process
->pid
);
3548 fprintf (stderr
, "\n");
3550 if (have_attached_inferiors_p ())
3552 fprintf (stderr
, "Detaching process(es):");
3554 for_each_process ([] (process_info
*process
) {
3555 if (process
->attached
)
3556 fprintf (stderr
, " %d", process
->pid
);
3559 fprintf (stderr
, "\n");
3562 /* Now we can kill or detach the inferiors. */
3563 for_each_process ([] (process_info
*process
) {
3564 int pid
= process
->pid
;
3566 if (process
->attached
)
3567 detach_inferior (process
);
3569 kill_inferior (process
);
3571 discard_queued_stop_replies (ptid_t (pid
));
3575 /* Value that will be passed to exit(3) when gdbserver exits. */
3576 static int exit_code
;
3578 /* Wrapper for detach_or_kill_for_exit that catches and prints
3582 detach_or_kill_for_exit_cleanup ()
3586 detach_or_kill_for_exit ();
3588 catch (const gdb_exception
&exception
)
3591 fprintf (stderr
, "Detach or kill failed: %s\n",
3597 /* Main function. This is called by the real "main" function,
3598 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
3600 static void ATTRIBUTE_NORETURN
3601 captured_main (int argc
, char *argv
[])
3606 const char *port
= NULL
;
3607 char **next_arg
= &argv
[1];
3608 volatile int multi_mode
= 0;
3609 volatile int attach
= 0;
3611 bool selftest
= false;
3613 const char *selftest_filter
= NULL
;
3616 current_directory
= getcwd (NULL
, 0);
3617 client_state
&cs
= get_client_state ();
3619 if (current_directory
== NULL
)
3621 error (_("Could not find current working directory: %s"),
3622 safe_strerror (errno
));
3625 while (*next_arg
!= NULL
&& **next_arg
== '-')
3627 if (strcmp (*next_arg
, "--version") == 0)
3629 gdbserver_version ();
3632 else if (strcmp (*next_arg
, "--help") == 0)
3634 gdbserver_usage (stdout
);
3637 else if (strcmp (*next_arg
, "--attach") == 0)
3639 else if (strcmp (*next_arg
, "--multi") == 0)
3641 else if (strcmp (*next_arg
, "--wrapper") == 0)
3648 while (*next_arg
!= NULL
&& strcmp (*next_arg
, "--") != 0)
3650 wrapper_argv
+= *next_arg
;
3651 wrapper_argv
+= ' ';
3655 if (!wrapper_argv
.empty ())
3657 /* Erase the last whitespace. */
3658 wrapper_argv
.erase (wrapper_argv
.end () - 1);
3661 if (next_arg
== tmp
|| *next_arg
== NULL
)
3663 gdbserver_usage (stderr
);
3667 /* Consume the "--". */
3670 else if (strcmp (*next_arg
, "--debug") == 0)
3672 else if (startswith (*next_arg
, "--debug-format="))
3674 std::string error_msg
3675 = parse_debug_format_options ((*next_arg
)
3676 + sizeof ("--debug-format=") - 1, 0);
3678 if (!error_msg
.empty ())
3680 fprintf (stderr
, "%s", error_msg
.c_str ());
3684 else if (strcmp (*next_arg
, "--remote-debug") == 0)
3686 else if (startswith (*next_arg
, "--debug-file="))
3687 debug_set_output ((*next_arg
) + sizeof ("--debug-file=") -1);
3688 else if (strcmp (*next_arg
, "--disable-packet") == 0)
3690 gdbserver_show_disableable (stdout
);
3693 else if (startswith (*next_arg
, "--disable-packet="))
3695 char *packets
= *next_arg
+= sizeof ("--disable-packet=") - 1;
3697 for (char *tok
= strtok_r (packets
, ",", &saveptr
);
3699 tok
= strtok_r (NULL
, ",", &saveptr
))
3701 if (strcmp ("vCont", tok
) == 0)
3702 disable_packet_vCont
= true;
3703 else if (strcmp ("Tthread", tok
) == 0)
3704 disable_packet_Tthread
= true;
3705 else if (strcmp ("qC", tok
) == 0)
3706 disable_packet_qC
= true;
3707 else if (strcmp ("qfThreadInfo", tok
) == 0)
3708 disable_packet_qfThreadInfo
= true;
3709 else if (strcmp ("T", tok
) == 0)
3710 disable_packet_T
= true;
3711 else if (strcmp ("threads", tok
) == 0)
3713 disable_packet_vCont
= true;
3714 disable_packet_Tthread
= true;
3715 disable_packet_qC
= true;
3716 disable_packet_qfThreadInfo
= true;
3720 fprintf (stderr
, "Don't know how to disable \"%s\".\n\n",
3722 gdbserver_show_disableable (stderr
);
3727 else if (strcmp (*next_arg
, "-") == 0)
3729 /* "-" specifies a stdio connection and is a form of port
3731 port
= STDIO_CONNECTION_NAME
;
3735 else if (strcmp (*next_arg
, "--disable-randomization") == 0)
3736 cs
.disable_randomization
= 1;
3737 else if (strcmp (*next_arg
, "--no-disable-randomization") == 0)
3738 cs
.disable_randomization
= 0;
3739 else if (strcmp (*next_arg
, "--startup-with-shell") == 0)
3740 startup_with_shell
= true;
3741 else if (strcmp (*next_arg
, "--no-startup-with-shell") == 0)
3742 startup_with_shell
= false;
3743 else if (strcmp (*next_arg
, "--once") == 0)
3745 else if (strcmp (*next_arg
, "--selftest") == 0)
3747 else if (startswith (*next_arg
, "--selftest="))
3751 selftest_filter
= *next_arg
+ strlen ("--selftest=");
3756 fprintf (stderr
, "Unknown argument: %s\n", *next_arg
);
3769 if ((port
== NULL
|| (!attach
&& !multi_mode
&& *next_arg
== NULL
))
3772 gdbserver_usage (stderr
);
3776 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
3777 opened by remote_prepare. */
3780 save_original_signals_state (false);
3782 /* We need to know whether the remote connection is stdio before
3783 starting the inferior. Inferiors created in this scenario have
3784 stdin,stdout redirected. So do this here before we call
3787 remote_prepare (port
);
3792 /* --attach used to come after PORT, so allow it there for
3794 if (*next_arg
!= NULL
&& strcmp (*next_arg
, "--attach") == 0)
3801 && (*next_arg
== NULL
3802 || (*next_arg
)[0] == '\0'
3803 || (pid
= strtoul (*next_arg
, &arg_end
, 0)) == 0
3805 || next_arg
[1] != NULL
))
3810 gdbserver_usage (stderr
);
3814 /* Gather information about the environment. */
3815 our_environ
= gdb_environ::from_host_environ ();
3817 initialize_async_io ();
3819 have_job_control ();
3820 if (target_supports_tracepoints ())
3821 initialize_tracepoint ();
3823 mem_buf
= (unsigned char *) xmalloc (PBUFSIZ
);
3828 selftests::run_tests (selftest_filter
);
3830 printf (_("Selftests have been disabled for this build.\n"));
3832 throw_quit ("Quit");
3835 if (pid
== 0 && *next_arg
!= NULL
)
3839 n
= argc
- (next_arg
- argv
);
3840 program_path
.set (make_unique_xstrdup (next_arg
[0]));
3841 for (i
= 1; i
< n
; i
++)
3842 program_args
.push_back (xstrdup (next_arg
[i
]));
3844 /* Wait till we are at first instruction in program. */
3845 target_create_inferior (program_path
.get (), program_args
);
3847 /* We are now (hopefully) stopped at the first instruction of
3848 the target process. This assumes that the target process was
3849 successfully created. */
3853 if (attach_inferior (pid
) == -1)
3854 error ("Attaching not supported on this target");
3856 /* Otherwise succeeded. */
3860 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
3861 cs
.last_status
.value
.integer
= 0;
3862 cs
.last_ptid
= minus_one_ptid
;
3865 SCOPE_EXIT
{ detach_or_kill_for_exit_cleanup (); };
3867 /* Don't report shared library events on the initial connection,
3868 even if some libraries are preloaded. Avoids the "stopped by
3869 shared library event" notice on gdb side. */
3872 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
3873 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
3878 if (!was_running
&& !multi_mode
)
3879 error ("No program to debug");
3884 cs
.multi_process
= 0;
3885 cs
.report_fork_events
= 0;
3886 cs
.report_vfork_events
= 0;
3887 cs
.report_exec_events
= 0;
3888 /* Be sure we're out of tfind mode. */
3889 cs
.current_traceframe
= -1;
3890 cs
.cont_thread
= null_ptid
;
3891 cs
.swbreak_feature
= 0;
3892 cs
.hwbreak_feature
= 0;
3893 cs
.vCont_supported
= 0;
3899 /* Wait for events. This will return when all event sources
3900 are removed from the event loop. */
3901 start_event_loop ();
3903 /* If an exit was requested (using the "monitor exit"
3904 command), terminate now. */
3906 throw_quit ("Quit");
3908 /* The only other way to get here is for getpkt to fail:
3910 - If --once was specified, we're done.
3912 - If not in extended-remote mode, and we're no longer
3913 debugging anything, simply exit: GDB has disconnected
3914 after processing the last process exit.
3916 - Otherwise, close the connection and reopen it at the
3918 if (run_once
|| (!extended_protocol
&& !target_running ()))
3919 throw_quit ("Quit");
3922 "Remote side has terminated connection. "
3923 "GDBserver will reopen the connection.\n");
3925 /* Get rid of any pending statuses. An eventual reconnection
3926 (by the same GDB instance or another) will refresh all its
3927 state from scratch. */
3928 discard_queued_stop_replies (minus_one_ptid
);
3929 for_each_thread ([] (thread_info
*thread
)
3931 thread
->status_pending_p
= 0;
3936 if (disconnected_tracing
)
3938 /* Try to enable non-stop/async mode, so we we can
3939 both wait for an async socket accept, and handle
3940 async target events simultaneously. There's also
3941 no point either in having the target always stop
3942 all threads, when we're going to pass signals
3943 down without informing GDB. */
3946 if (the_target
->start_non_stop (true))
3949 /* Detaching implicitly resumes all threads;
3950 simply disconnecting does not. */
3956 "Disconnected tracing disabled; "
3957 "stopping trace run.\n");
3962 catch (const gdb_exception_error
&exception
)
3965 fprintf (stderr
, "gdbserver: %s\n", exception
.what ());
3967 if (response_needed
)
3969 write_enn (cs
.own_buf
);
3970 putpkt (cs
.own_buf
);
3974 throw_quit ("Quit");
3979 /* Main function. */
3982 main (int argc
, char *argv
[])
3987 captured_main (argc
, argv
);
3989 catch (const gdb_exception
&exception
)
3991 if (exception
.reason
== RETURN_ERROR
)
3994 fprintf (stderr
, "%s\n", exception
.what ());
3995 fprintf (stderr
, "Exiting\n");
4002 gdb_assert_not_reached ("captured_main should never return");
4005 /* Process options coming from Z packets for a breakpoint. PACKET is
4006 the packet buffer. *PACKET is updated to point to the first char
4007 after the last processed option. */
4010 process_point_options (struct gdb_breakpoint
*bp
, const char **packet
)
4012 const char *dataptr
= *packet
;
4015 /* Check if data has the correct format. */
4016 if (*dataptr
!= ';')
4023 if (*dataptr
== ';')
4026 if (*dataptr
== 'X')
4028 /* Conditional expression. */
4030 debug_printf ("Found breakpoint condition.\n");
4031 if (!add_breakpoint_condition (bp
, &dataptr
))
4032 dataptr
= strchrnul (dataptr
, ';');
4034 else if (startswith (dataptr
, "cmds:"))
4036 dataptr
+= strlen ("cmds:");
4038 debug_printf ("Found breakpoint commands %s.\n", dataptr
);
4039 persist
= (*dataptr
== '1');
4041 if (add_breakpoint_commands (bp
, &dataptr
, persist
))
4042 dataptr
= strchrnul (dataptr
, ';');
4046 fprintf (stderr
, "Unknown token %c, ignoring.\n",
4048 /* Skip tokens until we find one that we recognize. */
4049 dataptr
= strchrnul (dataptr
, ';');
4055 /* Event loop callback that handles a serial event. The first byte in
4056 the serial buffer gets us here. We expect characters to arrive at
4057 a brisk pace, so we read the rest of the packet with a blocking
4061 process_serial_event (void)
4063 client_state
&cs
= get_client_state ();
4069 int new_packet_len
= -1;
4071 disable_async_io ();
4073 response_needed
= false;
4074 packet_len
= getpkt (cs
.own_buf
);
4075 if (packet_len
<= 0)
4078 /* Force an event loop break. */
4081 response_needed
= true;
4083 char ch
= cs
.own_buf
[0];
4087 handle_query (cs
.own_buf
, packet_len
, &new_packet_len
);
4090 handle_general_set (cs
.own_buf
);
4093 handle_detach (cs
.own_buf
);
4096 extended_protocol
= true;
4097 write_ok (cs
.own_buf
);
4100 handle_status (cs
.own_buf
);
4103 if (cs
.own_buf
[1] == 'c' || cs
.own_buf
[1] == 'g' || cs
.own_buf
[1] == 's')
4105 require_running_or_break (cs
.own_buf
);
4107 ptid_t thread_id
= read_ptid (&cs
.own_buf
[2], NULL
);
4109 if (thread_id
== null_ptid
|| thread_id
== minus_one_ptid
)
4110 thread_id
= null_ptid
;
4111 else if (thread_id
.is_pid ())
4113 /* The ptid represents a pid. */
4114 thread_info
*thread
= find_any_thread_of_pid (thread_id
.pid ());
4118 write_enn (cs
.own_buf
);
4122 thread_id
= thread
->id
;
4126 /* The ptid represents a lwp/tid. */
4127 if (find_thread_ptid (thread_id
) == NULL
)
4129 write_enn (cs
.own_buf
);
4134 if (cs
.own_buf
[1] == 'g')
4136 if (thread_id
== null_ptid
)
4138 /* GDB is telling us to choose any thread. Check if
4139 the currently selected thread is still valid. If
4140 it is not, select the first available. */
4141 thread_info
*thread
= find_thread_ptid (cs
.general_thread
);
4143 thread
= get_first_thread ();
4144 thread_id
= thread
->id
;
4147 cs
.general_thread
= thread_id
;
4148 set_desired_thread ();
4149 gdb_assert (current_thread
!= NULL
);
4151 else if (cs
.own_buf
[1] == 'c')
4152 cs
.cont_thread
= thread_id
;
4154 write_ok (cs
.own_buf
);
4158 /* Silently ignore it so that gdb can extend the protocol
4159 without compatibility headaches. */
4160 cs
.own_buf
[0] = '\0';
4164 require_running_or_break (cs
.own_buf
);
4165 if (cs
.current_traceframe
>= 0)
4167 struct regcache
*regcache
4168 = new_register_cache (current_target_desc ());
4170 if (fetch_traceframe_registers (cs
.current_traceframe
,
4172 registers_to_string (regcache
, cs
.own_buf
);
4174 write_enn (cs
.own_buf
);
4175 free_register_cache (regcache
);
4179 struct regcache
*regcache
;
4181 if (!set_desired_thread ())
4182 write_enn (cs
.own_buf
);
4185 regcache
= get_thread_regcache (current_thread
, 1);
4186 registers_to_string (regcache
, cs
.own_buf
);
4191 require_running_or_break (cs
.own_buf
);
4192 if (cs
.current_traceframe
>= 0)
4193 write_enn (cs
.own_buf
);
4196 struct regcache
*regcache
;
4198 if (!set_desired_thread ())
4199 write_enn (cs
.own_buf
);
4202 regcache
= get_thread_regcache (current_thread
, 1);
4203 registers_from_string (regcache
, &cs
.own_buf
[1]);
4204 write_ok (cs
.own_buf
);
4210 require_running_or_break (cs
.own_buf
);
4211 decode_m_packet (&cs
.own_buf
[1], &mem_addr
, &len
);
4212 int res
= gdb_read_memory (mem_addr
, mem_buf
, len
);
4214 write_enn (cs
.own_buf
);
4216 bin2hex (mem_buf
, cs
.own_buf
, res
);
4220 require_running_or_break (cs
.own_buf
);
4221 decode_M_packet (&cs
.own_buf
[1], &mem_addr
, &len
, &mem_buf
);
4222 if (gdb_write_memory (mem_addr
, mem_buf
, len
) == 0)
4223 write_ok (cs
.own_buf
);
4225 write_enn (cs
.own_buf
);
4228 require_running_or_break (cs
.own_buf
);
4229 if (decode_X_packet (&cs
.own_buf
[1], packet_len
- 1,
4230 &mem_addr
, &len
, &mem_buf
) < 0
4231 || gdb_write_memory (mem_addr
, mem_buf
, len
) != 0)
4232 write_enn (cs
.own_buf
);
4234 write_ok (cs
.own_buf
);
4237 require_running_or_break (cs
.own_buf
);
4238 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4239 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4240 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4243 myresume (cs
.own_buf
, 0, signal
);
4246 require_running_or_break (cs
.own_buf
);
4247 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4248 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4249 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4252 myresume (cs
.own_buf
, 1, signal
);
4255 require_running_or_break (cs
.own_buf
);
4257 myresume (cs
.own_buf
, 0, signal
);
4260 require_running_or_break (cs
.own_buf
);
4262 myresume (cs
.own_buf
, 1, signal
);
4264 case 'Z': /* insert_ ... */
4266 case 'z': /* remove_ ... */
4271 char type
= cs
.own_buf
[1];
4273 const int insert
= ch
== 'Z';
4274 const char *p
= &cs
.own_buf
[3];
4276 p
= unpack_varlen_hex (p
, &addr
);
4277 kind
= strtol (p
+ 1, &dataptr
, 16);
4281 struct gdb_breakpoint
*bp
;
4283 bp
= set_gdb_breakpoint (type
, addr
, kind
, &res
);
4288 /* GDB may have sent us a list of *point parameters to
4289 be evaluated on the target's side. Read such list
4290 here. If we already have a list of parameters, GDB
4291 is telling us to drop that list and use this one
4293 clear_breakpoint_conditions_and_commands (bp
);
4294 const char *options
= dataptr
;
4295 process_point_options (bp
, &options
);
4299 res
= delete_gdb_breakpoint (type
, addr
, kind
);
4302 write_ok (cs
.own_buf
);
4305 cs
.own_buf
[0] = '\0';
4307 write_enn (cs
.own_buf
);
4311 response_needed
= false;
4312 if (!target_running ())
4313 /* The packet we received doesn't make sense - but we can't
4314 reply to it, either. */
4317 fprintf (stderr
, "Killing all inferiors\n");
4319 for_each_process (kill_inferior_callback
);
4321 /* When using the extended protocol, we wait with no program
4322 running. The traditional protocol will exit instead. */
4323 if (extended_protocol
)
4325 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
4326 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
4334 require_running_or_break (cs
.own_buf
);
4336 ptid_t thread_id
= read_ptid (&cs
.own_buf
[1], NULL
);
4337 if (find_thread_ptid (thread_id
) == NULL
)
4339 write_enn (cs
.own_buf
);
4343 if (mythread_alive (thread_id
))
4344 write_ok (cs
.own_buf
);
4346 write_enn (cs
.own_buf
);
4350 response_needed
= false;
4352 /* Restarting the inferior is only supported in the extended
4354 if (extended_protocol
)
4356 if (target_running ())
4357 for_each_process (kill_inferior_callback
);
4359 fprintf (stderr
, "GDBserver restarting\n");
4361 /* Wait till we are at 1st instruction in prog. */
4362 if (program_path
.get () != NULL
)
4364 target_create_inferior (program_path
.get (), program_args
);
4366 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
4368 /* Stopped at the first instruction of the target
4370 cs
.general_thread
= cs
.last_ptid
;
4374 /* Something went wrong. */
4375 cs
.general_thread
= null_ptid
;
4380 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
4381 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
4387 /* It is a request we don't understand. Respond with an
4388 empty packet so that gdb knows that we don't support this
4390 cs
.own_buf
[0] = '\0';
4394 /* Extended (long) request. */
4395 handle_v_requests (cs
.own_buf
, packet_len
, &new_packet_len
);
4399 /* It is a request we don't understand. Respond with an empty
4400 packet so that gdb knows that we don't support this
4402 cs
.own_buf
[0] = '\0';
4406 if (new_packet_len
!= -1)
4407 putpkt_binary (cs
.own_buf
, new_packet_len
);
4409 putpkt (cs
.own_buf
);
4411 response_needed
= false;
4419 /* Event-loop callback for serial events. */
4422 handle_serial_event (int err
, gdb_client_data client_data
)
4425 debug_printf ("handling possible serial event\n");
4427 /* Really handle it. */
4428 if (process_serial_event () < 0)
4430 keep_processing_events
= false;
4434 /* Be sure to not change the selected thread behind GDB's back.
4435 Important in the non-stop mode asynchronous protocol. */
4436 set_desired_thread ();
4439 /* Push a stop notification on the notification queue. */
4442 push_stop_notification (ptid_t ptid
, struct target_waitstatus
*status
)
4444 struct vstop_notif
*vstop_notif
= new struct vstop_notif
;
4446 vstop_notif
->status
= *status
;
4447 vstop_notif
->ptid
= ptid
;
4448 /* Push Stop notification. */
4449 notif_push (¬if_stop
, vstop_notif
);
4452 /* Event-loop callback for target events. */
4455 handle_target_event (int err
, gdb_client_data client_data
)
4457 client_state
&cs
= get_client_state ();
4459 debug_printf ("handling possible target event\n");
4461 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
,
4464 if (cs
.last_status
.kind
== TARGET_WAITKIND_NO_RESUMED
)
4466 if (gdb_connected () && report_no_resumed
)
4467 push_stop_notification (null_ptid
, &cs
.last_status
);
4469 else if (cs
.last_status
.kind
!= TARGET_WAITKIND_IGNORE
)
4471 int pid
= cs
.last_ptid
.pid ();
4472 struct process_info
*process
= find_process_pid (pid
);
4473 int forward_event
= !gdb_connected () || process
->gdb_detached
;
4475 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
4476 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
4478 mark_breakpoints_out (process
);
4479 target_mourn_inferior (cs
.last_ptid
);
4481 else if (cs
.last_status
.kind
== TARGET_WAITKIND_THREAD_EXITED
)
4485 /* We're reporting this thread as stopped. Update its
4486 "want-stopped" state to what the client wants, until it
4487 gets a new resume action. */
4488 current_thread
->last_resume_kind
= resume_stop
;
4489 current_thread
->last_status
= cs
.last_status
;
4494 if (!target_running ())
4496 /* The last process exited. We're done. */
4500 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
4501 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
4502 || cs
.last_status
.kind
== TARGET_WAITKIND_THREAD_EXITED
)
4506 /* A thread stopped with a signal, but gdb isn't
4507 connected to handle it. Pass it down to the
4508 inferior, as if it wasn't being traced. */
4509 enum gdb_signal signal
;
4512 debug_printf ("GDB not connected; forwarding event %d for"
4514 (int) cs
.last_status
.kind
,
4515 target_pid_to_str (cs
.last_ptid
));
4517 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
4518 signal
= cs
.last_status
.value
.sig
;
4520 signal
= GDB_SIGNAL_0
;
4521 target_continue (cs
.last_ptid
, signal
);
4525 push_stop_notification (cs
.last_ptid
, &cs
.last_status
);
4528 /* Be sure to not change the selected thread behind GDB's back.
4529 Important in the non-stop mode asynchronous protocol. */
4530 set_desired_thread ();
4533 /* See gdbsupport/event-loop.h. */
4536 invoke_async_signal_handlers ()
4541 /* See gdbsupport/event-loop.h. */
4544 check_async_event_handlers ()
4549 /* See gdbsupport/errors.h */
4558 /* See gdbsupport/gdb_select.h. */
4561 gdb_select (int n
, fd_set
*readfds
, fd_set
*writefds
,
4562 fd_set
*exceptfds
, struct timeval
*timeout
)
4564 return select (n
, readfds
, writefds
, exceptfds
, timeout
);
4575 } // namespace selftests
4576 #endif /* GDB_SELF_TEST */