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 event-loop-debug <0|1>\n");
959 monitor_output (" Enable event loop debugging messages\n");
960 monitor_output (" set debug-format option1[,option2,...]\n");
961 monitor_output (" Add additional information to debugging messages\n");
962 monitor_output (" Options: all, none");
963 monitor_output (", timestamp");
964 monitor_output ("\n");
965 monitor_output (" exit\n");
966 monitor_output (" Quit GDBserver\n");
969 /* Read trace frame or inferior memory. Returns the number of bytes
970 actually read, zero when no further transfer is possible, and -1 on
971 error. Return of a positive value smaller than LEN does not
972 indicate there's no more to be read, only the end of the transfer.
973 E.g., when GDB reads memory from a traceframe, a first request may
974 be served from a memory block that does not cover the whole request
975 length. A following request gets the rest served from either
976 another block (of the same traceframe) or from the read-only
980 gdb_read_memory (CORE_ADDR memaddr
, unsigned char *myaddr
, int len
)
982 client_state
&cs
= get_client_state ();
985 if (cs
.current_traceframe
>= 0)
988 ULONGEST length
= len
;
990 if (traceframe_read_mem (cs
.current_traceframe
,
991 memaddr
, myaddr
, len
, &nbytes
))
993 /* Data read from trace buffer, we're done. */
996 if (!in_readonly_region (memaddr
, length
))
998 /* Otherwise we have a valid readonly case, fall through. */
999 /* (assume no half-trace half-real blocks for now) */
1002 res
= prepare_to_access_memory ();
1005 if (set_desired_thread ())
1006 res
= read_inferior_memory (memaddr
, myaddr
, len
);
1009 done_accessing_memory ();
1011 return res
== 0 ? len
: -1;
1017 /* Write trace frame or inferior memory. Actually, writing to trace
1018 frames is forbidden. */
1021 gdb_write_memory (CORE_ADDR memaddr
, const unsigned char *myaddr
, int len
)
1023 client_state
&cs
= get_client_state ();
1024 if (cs
.current_traceframe
>= 0)
1030 ret
= prepare_to_access_memory ();
1033 if (set_desired_thread ())
1034 ret
= target_write_memory (memaddr
, myaddr
, len
);
1037 done_accessing_memory ();
1043 /* Subroutine of handle_search_memory to simplify it. */
1046 handle_search_memory_1 (CORE_ADDR start_addr
, CORE_ADDR search_space_len
,
1047 gdb_byte
*pattern
, unsigned pattern_len
,
1048 gdb_byte
*search_buf
,
1049 unsigned chunk_size
, unsigned search_buf_size
,
1050 CORE_ADDR
*found_addrp
)
1052 /* Prime the search buffer. */
1054 if (gdb_read_memory (start_addr
, search_buf
, search_buf_size
)
1057 warning ("Unable to access %ld bytes of target "
1058 "memory at 0x%lx, halting search.",
1059 (long) search_buf_size
, (long) start_addr
);
1063 /* Perform the search.
1065 The loop is kept simple by allocating [N + pattern-length - 1] bytes.
1066 When we've scanned N bytes we copy the trailing bytes to the start and
1067 read in another N bytes. */
1069 while (search_space_len
>= pattern_len
)
1071 gdb_byte
*found_ptr
;
1072 unsigned nr_search_bytes
= (search_space_len
< search_buf_size
1076 found_ptr
= (gdb_byte
*) memmem (search_buf
, nr_search_bytes
, pattern
,
1079 if (found_ptr
!= NULL
)
1081 CORE_ADDR found_addr
= start_addr
+ (found_ptr
- search_buf
);
1082 *found_addrp
= found_addr
;
1086 /* Not found in this chunk, skip to next chunk. */
1088 /* Don't let search_space_len wrap here, it's unsigned. */
1089 if (search_space_len
>= chunk_size
)
1090 search_space_len
-= chunk_size
;
1092 search_space_len
= 0;
1094 if (search_space_len
>= pattern_len
)
1096 unsigned keep_len
= search_buf_size
- chunk_size
;
1097 CORE_ADDR read_addr
= start_addr
+ chunk_size
+ keep_len
;
1100 /* Copy the trailing part of the previous iteration to the front
1101 of the buffer for the next iteration. */
1102 memcpy (search_buf
, search_buf
+ chunk_size
, keep_len
);
1104 nr_to_read
= (search_space_len
- keep_len
< chunk_size
1105 ? search_space_len
- keep_len
1108 if (gdb_read_memory (read_addr
, search_buf
+ keep_len
,
1109 nr_to_read
) != nr_to_read
)
1111 warning ("Unable to access %ld bytes of target memory "
1112 "at 0x%lx, halting search.",
1113 (long) nr_to_read
, (long) read_addr
);
1117 start_addr
+= chunk_size
;
1126 /* Handle qSearch:memory packets. */
1129 handle_search_memory (char *own_buf
, int packet_len
)
1131 CORE_ADDR start_addr
;
1132 CORE_ADDR search_space_len
;
1134 unsigned int pattern_len
;
1135 /* NOTE: also defined in find.c testcase. */
1136 #define SEARCH_CHUNK_SIZE 16000
1137 const unsigned chunk_size
= SEARCH_CHUNK_SIZE
;
1138 /* Buffer to hold memory contents for searching. */
1139 gdb_byte
*search_buf
;
1140 unsigned search_buf_size
;
1142 CORE_ADDR found_addr
;
1143 int cmd_name_len
= sizeof ("qSearch:memory:") - 1;
1145 pattern
= (gdb_byte
*) malloc (packet_len
);
1146 if (pattern
== NULL
)
1148 error ("Unable to allocate memory to perform the search");
1149 strcpy (own_buf
, "E00");
1152 if (decode_search_memory_packet (own_buf
+ cmd_name_len
,
1153 packet_len
- cmd_name_len
,
1154 &start_addr
, &search_space_len
,
1155 pattern
, &pattern_len
) < 0)
1158 error ("Error in parsing qSearch:memory packet");
1159 strcpy (own_buf
, "E00");
1163 search_buf_size
= chunk_size
+ pattern_len
- 1;
1165 /* No point in trying to allocate a buffer larger than the search space. */
1166 if (search_space_len
< search_buf_size
)
1167 search_buf_size
= search_space_len
;
1169 search_buf
= (gdb_byte
*) malloc (search_buf_size
);
1170 if (search_buf
== NULL
)
1173 error ("Unable to allocate memory to perform the search");
1174 strcpy (own_buf
, "E00");
1178 found
= handle_search_memory_1 (start_addr
, search_space_len
,
1179 pattern
, pattern_len
,
1180 search_buf
, chunk_size
, search_buf_size
,
1184 sprintf (own_buf
, "1,%lx", (long) found_addr
);
1185 else if (found
== 0)
1186 strcpy (own_buf
, "0");
1188 strcpy (own_buf
, "E00");
1194 /* Handle the "D" packet. */
1197 handle_detach (char *own_buf
)
1199 client_state
&cs
= get_client_state ();
1201 process_info
*process
;
1203 if (cs
.multi_process
)
1206 int pid
= strtol (&own_buf
[2], NULL
, 16);
1208 process
= find_process_pid (pid
);
1212 process
= (current_thread
!= nullptr
1213 ? get_thread_process (current_thread
)
1217 if (process
== NULL
)
1219 write_enn (own_buf
);
1223 if ((tracing
&& disconnected_tracing
) || any_persistent_commands (process
))
1225 if (tracing
&& disconnected_tracing
)
1227 "Disconnected tracing in effect, "
1228 "leaving gdbserver attached to the process\n");
1230 if (any_persistent_commands (process
))
1232 "Persistent commands are present, "
1233 "leaving gdbserver attached to the process\n");
1235 /* Make sure we're in non-stop/async mode, so we we can both
1236 wait for an async socket accept, and handle async target
1237 events simultaneously. There's also no point either in
1238 having the target stop all threads, when we're going to
1239 pass signals down without informing GDB. */
1243 debug_printf ("Forcing non-stop mode\n");
1246 the_target
->start_non_stop (true);
1249 process
->gdb_detached
= 1;
1251 /* Detaching implicitly resumes all threads. */
1252 target_continue_no_signal (minus_one_ptid
);
1258 fprintf (stderr
, "Detaching from process %d\n", process
->pid
);
1261 /* We'll need this after PROCESS has been destroyed. */
1262 int pid
= process
->pid
;
1264 if (detach_inferior (process
) != 0)
1265 write_enn (own_buf
);
1268 discard_queued_stop_replies (ptid_t (pid
));
1271 if (extended_protocol
|| target_running ())
1273 /* There is still at least one inferior remaining or
1274 we are in extended mode, so don't terminate gdbserver,
1275 and instead treat this like a normal program exit. */
1276 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
1277 cs
.last_status
.value
.integer
= 0;
1278 cs
.last_ptid
= ptid_t (pid
);
1280 current_thread
= NULL
;
1287 /* If we are attached, then we can exit. Otherwise, we
1288 need to hang around doing nothing, until the child is
1290 join_inferior (pid
);
1296 /* Parse options to --debug-format= and "monitor set debug-format".
1297 ARG is the text after "--debug-format=" or "monitor set debug-format".
1298 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1299 This triggers calls to monitor_output.
1300 The result is an empty string if all options were parsed ok, otherwise an
1301 error message which the caller must free.
1303 N.B. These commands affect all debug format settings, they are not
1304 cumulative. If a format is not specified, it is turned off.
1305 However, we don't go to extra trouble with things like
1306 "monitor set debug-format all,none,timestamp".
1307 Instead we just parse them one at a time, in order.
1309 The syntax for "monitor set debug" we support here is not identical
1310 to gdb's "set debug foo on|off" because we also use this function to
1311 parse "--debug-format=foo,bar". */
1314 parse_debug_format_options (const char *arg
, int is_monitor
)
1316 /* First turn all debug format options off. */
1317 debug_timestamp
= 0;
1319 /* First remove leading spaces, for "monitor set debug-format". */
1320 while (isspace (*arg
))
1323 std::vector
<gdb::unique_xmalloc_ptr
<char>> options
1324 = delim_string_to_char_ptr_vec (arg
, ',');
1326 for (const gdb::unique_xmalloc_ptr
<char> &option
: options
)
1328 if (strcmp (option
.get (), "all") == 0)
1330 debug_timestamp
= 1;
1332 monitor_output ("All extra debug format options enabled.\n");
1334 else if (strcmp (option
.get (), "none") == 0)
1336 debug_timestamp
= 0;
1338 monitor_output ("All extra debug format options disabled.\n");
1340 else if (strcmp (option
.get (), "timestamp") == 0)
1342 debug_timestamp
= 1;
1344 monitor_output ("Timestamps will be added to debug output.\n");
1346 else if (*option
== '\0')
1348 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1352 return string_printf ("Unknown debug-format argument: \"%s\"\n",
1356 return std::string ();
1359 /* Handle monitor commands not handled by target-specific handlers. */
1362 handle_monitor_command (char *mon
, char *own_buf
)
1364 if (strcmp (mon
, "set debug 1") == 0)
1367 monitor_output ("Debug output enabled.\n");
1369 else if (strcmp (mon
, "set debug 0") == 0)
1372 monitor_output ("Debug output disabled.\n");
1374 else if (strcmp (mon
, "set debug-hw-points 1") == 0)
1376 show_debug_regs
= 1;
1377 monitor_output ("H/W point debugging output enabled.\n");
1379 else if (strcmp (mon
, "set debug-hw-points 0") == 0)
1381 show_debug_regs
= 0;
1382 monitor_output ("H/W point debugging output disabled.\n");
1384 else if (strcmp (mon
, "set remote-debug 1") == 0)
1387 monitor_output ("Protocol debug output enabled.\n");
1389 else if (strcmp (mon
, "set remote-debug 0") == 0)
1392 monitor_output ("Protocol debug output disabled.\n");
1394 else if (strcmp (mon
, "set event-loop-debug 1") == 0)
1396 debug_event_loop
= debug_event_loop_kind::ALL
;
1397 monitor_output ("Event loop debug output enabled.\n");
1399 else if (strcmp (mon
, "set event-loop-debug 0") == 0)
1401 debug_event_loop
= debug_event_loop_kind::OFF
;
1402 monitor_output ("Event loop debug output disabled.\n");
1404 else if (startswith (mon
, "set debug-format "))
1406 std::string error_msg
1407 = parse_debug_format_options (mon
+ sizeof ("set debug-format ") - 1,
1410 if (!error_msg
.empty ())
1412 monitor_output (error_msg
.c_str ());
1413 monitor_show_help ();
1414 write_enn (own_buf
);
1417 else if (strcmp (mon
, "set debug-file") == 0)
1418 debug_set_output (nullptr);
1419 else if (startswith (mon
, "set debug-file "))
1420 debug_set_output (mon
+ sizeof ("set debug-file ") - 1);
1421 else if (strcmp (mon
, "help") == 0)
1422 monitor_show_help ();
1423 else if (strcmp (mon
, "exit") == 0)
1424 exit_requested
= true;
1427 monitor_output ("Unknown monitor command.\n\n");
1428 monitor_show_help ();
1429 write_enn (own_buf
);
1433 /* Associates a callback with each supported qXfer'able object. */
1437 /* The object this handler handles. */
1440 /* Request that the target transfer up to LEN 8-bit bytes of the
1441 target's OBJECT. The OFFSET, for a seekable object, specifies
1442 the starting point. The ANNEX can be used to provide additional
1443 data-specific information to the target.
1445 Return the number of bytes actually transfered, zero when no
1446 further transfer is possible, -1 on error, -2 when the transfer
1447 is not supported, and -3 on a verbose error message that should
1448 be preserved. Return of a positive value smaller than LEN does
1449 not indicate the end of the object, only the end of the transfer.
1451 One, and only one, of readbuf or writebuf must be non-NULL. */
1452 int (*xfer
) (const char *annex
,
1453 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1454 ULONGEST offset
, LONGEST len
);
1457 /* Handle qXfer:auxv:read. */
1460 handle_qxfer_auxv (const char *annex
,
1461 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1462 ULONGEST offset
, LONGEST len
)
1464 if (!the_target
->supports_read_auxv () || writebuf
!= NULL
)
1467 if (annex
[0] != '\0' || current_thread
== NULL
)
1470 return the_target
->read_auxv (offset
, readbuf
, len
);
1473 /* Handle qXfer:exec-file:read. */
1476 handle_qxfer_exec_file (const char *annex
,
1477 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1478 ULONGEST offset
, LONGEST len
)
1484 if (!the_target
->supports_pid_to_exec_file () || writebuf
!= NULL
)
1487 if (annex
[0] == '\0')
1489 if (current_thread
== NULL
)
1492 pid
= pid_of (current_thread
);
1496 annex
= unpack_varlen_hex (annex
, &pid
);
1497 if (annex
[0] != '\0')
1504 file
= the_target
->pid_to_exec_file (pid
);
1508 total_len
= strlen (file
);
1510 if (offset
> total_len
)
1513 if (offset
+ len
> total_len
)
1514 len
= total_len
- offset
;
1516 memcpy (readbuf
, file
+ offset
, len
);
1520 /* Handle qXfer:features:read. */
1523 handle_qxfer_features (const char *annex
,
1524 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1525 ULONGEST offset
, LONGEST len
)
1527 const char *document
;
1530 if (writebuf
!= NULL
)
1533 if (!target_running ())
1536 /* Grab the correct annex. */
1537 document
= get_features_xml (annex
);
1538 if (document
== NULL
)
1541 total_len
= strlen (document
);
1543 if (offset
> total_len
)
1546 if (offset
+ len
> total_len
)
1547 len
= total_len
- offset
;
1549 memcpy (readbuf
, document
+ offset
, len
);
1553 /* Handle qXfer:libraries:read. */
1556 handle_qxfer_libraries (const char *annex
,
1557 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1558 ULONGEST offset
, LONGEST len
)
1560 if (writebuf
!= NULL
)
1563 if (annex
[0] != '\0' || current_thread
== NULL
)
1566 std::string document
= "<library-list version=\"1.0\">\n";
1568 for (const dll_info
&dll
: all_dlls
)
1569 document
+= string_printf
1570 (" <library name=\"%s\"><segment address=\"0x%s\"/></library>\n",
1571 dll
.name
.c_str (), paddress (dll
.base_addr
));
1573 document
+= "</library-list>\n";
1575 if (offset
> document
.length ())
1578 if (offset
+ len
> document
.length ())
1579 len
= document
.length () - offset
;
1581 memcpy (readbuf
, &document
[offset
], len
);
1586 /* Handle qXfer:libraries-svr4:read. */
1589 handle_qxfer_libraries_svr4 (const char *annex
,
1590 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1591 ULONGEST offset
, LONGEST len
)
1593 if (writebuf
!= NULL
)
1596 if (current_thread
== NULL
1597 || !the_target
->supports_qxfer_libraries_svr4 ())
1600 return the_target
->qxfer_libraries_svr4 (annex
, readbuf
, writebuf
,
1604 /* Handle qXfer:osadata:read. */
1607 handle_qxfer_osdata (const char *annex
,
1608 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1609 ULONGEST offset
, LONGEST len
)
1611 if (!the_target
->supports_qxfer_osdata () || writebuf
!= NULL
)
1614 return the_target
->qxfer_osdata (annex
, readbuf
, NULL
, offset
, len
);
1617 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1620 handle_qxfer_siginfo (const char *annex
,
1621 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1622 ULONGEST offset
, LONGEST len
)
1624 if (!the_target
->supports_qxfer_siginfo ())
1627 if (annex
[0] != '\0' || current_thread
== NULL
)
1630 return the_target
->qxfer_siginfo (annex
, readbuf
, writebuf
, offset
, len
);
1633 /* Handle qXfer:statictrace:read. */
1636 handle_qxfer_statictrace (const char *annex
,
1637 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1638 ULONGEST offset
, LONGEST len
)
1640 client_state
&cs
= get_client_state ();
1643 if (writebuf
!= NULL
)
1646 if (annex
[0] != '\0' || current_thread
== NULL
1647 || cs
.current_traceframe
== -1)
1650 if (traceframe_read_sdata (cs
.current_traceframe
, offset
,
1651 readbuf
, len
, &nbytes
))
1656 /* Helper for handle_qxfer_threads_proper.
1657 Emit the XML to describe the thread of INF. */
1660 handle_qxfer_threads_worker (thread_info
*thread
, struct buffer
*buffer
)
1662 ptid_t ptid
= ptid_of (thread
);
1664 int core
= target_core_of_thread (ptid
);
1666 const char *name
= target_thread_name (ptid
);
1669 bool handle_status
= target_thread_handle (ptid
, &handle
, &handle_len
);
1671 write_ptid (ptid_s
, ptid
);
1673 buffer_xml_printf (buffer
, "<thread id=\"%s\"", ptid_s
);
1677 sprintf (core_s
, "%d", core
);
1678 buffer_xml_printf (buffer
, " core=\"%s\"", core_s
);
1682 buffer_xml_printf (buffer
, " name=\"%s\"", name
);
1686 char *handle_s
= (char *) alloca (handle_len
* 2 + 1);
1687 bin2hex (handle
, handle_s
, handle_len
);
1688 buffer_xml_printf (buffer
, " handle=\"%s\"", handle_s
);
1691 buffer_xml_printf (buffer
, "/>\n");
1694 /* Helper for handle_qxfer_threads. Return true on success, false
1698 handle_qxfer_threads_proper (struct buffer
*buffer
)
1700 client_state
&cs
= get_client_state ();
1702 scoped_restore save_current_thread
1703 = make_scoped_restore (¤t_thread
);
1704 scoped_restore save_current_general_thread
1705 = make_scoped_restore (&cs
.general_thread
);
1707 buffer_grow_str (buffer
, "<threads>\n");
1709 process_info
*error_proc
= find_process ([&] (process_info
*process
)
1711 /* The target may need to access memory and registers (e.g. via
1712 libthread_db) to fetch thread properties. Prepare for memory
1713 access here, so that we potentially pause threads just once
1714 for all accesses. Note that even if someday we stop needing
1715 to pause threads to access memory, we will need to be able to
1716 access registers, or other ptrace accesses like
1717 PTRACE_GET_THREAD_AREA. */
1719 /* Need to switch to each process in turn, because
1720 prepare_to_access_memory prepares for an access in the
1721 current process pointed to by general_thread. */
1722 switch_to_process (process
);
1723 cs
.general_thread
= current_thread
->id
;
1725 int res
= prepare_to_access_memory ();
1728 for_each_thread (process
->pid
, [&] (thread_info
*thread
)
1730 handle_qxfer_threads_worker (thread
, buffer
);
1733 done_accessing_memory ();
1740 buffer_grow_str0 (buffer
, "</threads>\n");
1741 return error_proc
== nullptr;
1744 /* Handle qXfer:threads:read. */
1747 handle_qxfer_threads (const char *annex
,
1748 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1749 ULONGEST offset
, LONGEST len
)
1751 static char *result
= 0;
1752 static unsigned int result_length
= 0;
1754 if (writebuf
!= NULL
)
1757 if (annex
[0] != '\0')
1762 struct buffer buffer
;
1763 /* When asked for data at offset 0, generate everything and store into
1764 'result'. Successive reads will be served off 'result'. */
1768 buffer_init (&buffer
);
1770 bool res
= handle_qxfer_threads_proper (&buffer
);
1772 result
= buffer_finish (&buffer
);
1773 result_length
= strlen (result
);
1774 buffer_free (&buffer
);
1780 if (offset
>= result_length
)
1782 /* We're out of data. */
1789 if (len
> result_length
- offset
)
1790 len
= result_length
- offset
;
1792 memcpy (readbuf
, result
+ offset
, len
);
1797 /* Handle qXfer:traceframe-info:read. */
1800 handle_qxfer_traceframe_info (const char *annex
,
1801 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1802 ULONGEST offset
, LONGEST len
)
1804 client_state
&cs
= get_client_state ();
1805 static char *result
= 0;
1806 static unsigned int result_length
= 0;
1808 if (writebuf
!= NULL
)
1811 if (!target_running () || annex
[0] != '\0' || cs
.current_traceframe
== -1)
1816 struct buffer buffer
;
1818 /* When asked for data at offset 0, generate everything and
1819 store into 'result'. Successive reads will be served off
1823 buffer_init (&buffer
);
1825 traceframe_read_info (cs
.current_traceframe
, &buffer
);
1827 result
= buffer_finish (&buffer
);
1828 result_length
= strlen (result
);
1829 buffer_free (&buffer
);
1832 if (offset
>= result_length
)
1834 /* We're out of data. */
1841 if (len
> result_length
- offset
)
1842 len
= result_length
- offset
;
1844 memcpy (readbuf
, result
+ offset
, len
);
1848 /* Handle qXfer:fdpic:read. */
1851 handle_qxfer_fdpic (const char *annex
, gdb_byte
*readbuf
,
1852 const gdb_byte
*writebuf
, ULONGEST offset
, LONGEST len
)
1854 if (!the_target
->supports_read_loadmap ())
1857 if (current_thread
== NULL
)
1860 return the_target
->read_loadmap (annex
, offset
, readbuf
, len
);
1863 /* Handle qXfer:btrace:read. */
1866 handle_qxfer_btrace (const char *annex
,
1867 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1868 ULONGEST offset
, LONGEST len
)
1870 client_state
&cs
= get_client_state ();
1871 static struct buffer cache
;
1872 struct thread_info
*thread
;
1873 enum btrace_read_type type
;
1876 if (writebuf
!= NULL
)
1879 if (cs
.general_thread
== null_ptid
1880 || cs
.general_thread
== minus_one_ptid
)
1882 strcpy (cs
.own_buf
, "E.Must select a single thread.");
1886 thread
= find_thread_ptid (cs
.general_thread
);
1889 strcpy (cs
.own_buf
, "E.No such thread.");
1893 if (thread
->btrace
== NULL
)
1895 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
1899 if (strcmp (annex
, "all") == 0)
1900 type
= BTRACE_READ_ALL
;
1901 else if (strcmp (annex
, "new") == 0)
1902 type
= BTRACE_READ_NEW
;
1903 else if (strcmp (annex
, "delta") == 0)
1904 type
= BTRACE_READ_DELTA
;
1907 strcpy (cs
.own_buf
, "E.Bad annex.");
1913 buffer_free (&cache
);
1917 result
= target_read_btrace (thread
->btrace
, &cache
, type
);
1919 memcpy (cs
.own_buf
, cache
.buffer
, cache
.used_size
);
1921 catch (const gdb_exception_error
&exception
)
1923 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
1930 else if (offset
> cache
.used_size
)
1932 buffer_free (&cache
);
1936 if (len
> cache
.used_size
- offset
)
1937 len
= cache
.used_size
- offset
;
1939 memcpy (readbuf
, cache
.buffer
+ offset
, len
);
1944 /* Handle qXfer:btrace-conf:read. */
1947 handle_qxfer_btrace_conf (const char *annex
,
1948 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1949 ULONGEST offset
, LONGEST len
)
1951 client_state
&cs
= get_client_state ();
1952 static struct buffer cache
;
1953 struct thread_info
*thread
;
1956 if (writebuf
!= NULL
)
1959 if (annex
[0] != '\0')
1962 if (cs
.general_thread
== null_ptid
1963 || cs
.general_thread
== minus_one_ptid
)
1965 strcpy (cs
.own_buf
, "E.Must select a single thread.");
1969 thread
= find_thread_ptid (cs
.general_thread
);
1972 strcpy (cs
.own_buf
, "E.No such thread.");
1976 if (thread
->btrace
== NULL
)
1978 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
1984 buffer_free (&cache
);
1988 result
= target_read_btrace_conf (thread
->btrace
, &cache
);
1990 memcpy (cs
.own_buf
, cache
.buffer
, cache
.used_size
);
1992 catch (const gdb_exception_error
&exception
)
1994 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
2001 else if (offset
> cache
.used_size
)
2003 buffer_free (&cache
);
2007 if (len
> cache
.used_size
- offset
)
2008 len
= cache
.used_size
- offset
;
2010 memcpy (readbuf
, cache
.buffer
+ offset
, len
);
2015 static const struct qxfer qxfer_packets
[] =
2017 { "auxv", handle_qxfer_auxv
},
2018 { "btrace", handle_qxfer_btrace
},
2019 { "btrace-conf", handle_qxfer_btrace_conf
},
2020 { "exec-file", handle_qxfer_exec_file
},
2021 { "fdpic", handle_qxfer_fdpic
},
2022 { "features", handle_qxfer_features
},
2023 { "libraries", handle_qxfer_libraries
},
2024 { "libraries-svr4", handle_qxfer_libraries_svr4
},
2025 { "osdata", handle_qxfer_osdata
},
2026 { "siginfo", handle_qxfer_siginfo
},
2027 { "statictrace", handle_qxfer_statictrace
},
2028 { "threads", handle_qxfer_threads
},
2029 { "traceframe-info", handle_qxfer_traceframe_info
},
2033 handle_qxfer (char *own_buf
, int packet_len
, int *new_packet_len_p
)
2041 if (!startswith (own_buf
, "qXfer:"))
2044 /* Grab the object, r/w and annex. */
2045 if (decode_xfer (own_buf
+ 6, &object
, &rw
, &annex
, &offset
) < 0)
2047 write_enn (own_buf
);
2052 i
< sizeof (qxfer_packets
) / sizeof (qxfer_packets
[0]);
2055 const struct qxfer
*q
= &qxfer_packets
[i
];
2057 if (strcmp (object
, q
->object
) == 0)
2059 if (strcmp (rw
, "read") == 0)
2061 unsigned char *data
;
2066 /* Grab the offset and length. */
2067 if (decode_xfer_read (offset
, &ofs
, &len
) < 0)
2069 write_enn (own_buf
);
2073 /* Read one extra byte, as an indicator of whether there is
2075 if (len
> PBUFSIZ
- 2)
2077 data
= (unsigned char *) malloc (len
+ 1);
2080 write_enn (own_buf
);
2083 n
= (*q
->xfer
) (annex
, data
, NULL
, ofs
, len
+ 1);
2091 /* Preserve error message. */
2094 write_enn (own_buf
);
2096 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, len
, 1);
2098 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, n
, 0);
2103 else if (strcmp (rw
, "write") == 0)
2108 unsigned char *data
;
2110 strcpy (own_buf
, "E00");
2111 data
= (unsigned char *) malloc (packet_len
- (offset
- own_buf
));
2114 write_enn (own_buf
);
2117 if (decode_xfer_write (offset
, packet_len
- (offset
- own_buf
),
2118 &ofs
, &len
, data
) < 0)
2121 write_enn (own_buf
);
2125 n
= (*q
->xfer
) (annex
, NULL
, data
, ofs
, len
);
2133 /* Preserve error message. */
2136 write_enn (own_buf
);
2138 sprintf (own_buf
, "%x", n
);
2151 /* Compute 32 bit CRC from inferior memory.
2153 On success, return 32 bit CRC.
2154 On failure, return (unsigned long long) -1. */
2156 static unsigned long long
2157 crc32 (CORE_ADDR base
, int len
, unsigned int crc
)
2161 unsigned char byte
= 0;
2163 /* Return failure if memory read fails. */
2164 if (read_inferior_memory (base
, &byte
, 1) != 0)
2165 return (unsigned long long) -1;
2167 crc
= xcrc32 (&byte
, 1, crc
);
2170 return (unsigned long long) crc
;
2173 /* Add supported btrace packets to BUF. */
2176 supported_btrace_packets (char *buf
)
2178 strcat (buf
, ";Qbtrace:bts+");
2179 strcat (buf
, ";Qbtrace-conf:bts:size+");
2180 strcat (buf
, ";Qbtrace:pt+");
2181 strcat (buf
, ";Qbtrace-conf:pt:size+");
2182 strcat (buf
, ";Qbtrace:off+");
2183 strcat (buf
, ";qXfer:btrace:read+");
2184 strcat (buf
, ";qXfer:btrace-conf:read+");
2187 /* Handle all of the extended 'q' packets. */
2190 handle_query (char *own_buf
, int packet_len
, int *new_packet_len_p
)
2192 client_state
&cs
= get_client_state ();
2193 static std::list
<thread_info
*>::const_iterator thread_iter
;
2195 /* Reply the current thread id. */
2196 if (strcmp ("qC", own_buf
) == 0 && !disable_packet_qC
)
2199 require_running_or_return (own_buf
);
2201 if (cs
.general_thread
!= null_ptid
&& cs
.general_thread
!= minus_one_ptid
)
2202 ptid
= cs
.general_thread
;
2205 thread_iter
= all_threads
.begin ();
2206 ptid
= (*thread_iter
)->id
;
2209 sprintf (own_buf
, "QC");
2211 write_ptid (own_buf
, ptid
);
2215 if (strcmp ("qSymbol::", own_buf
) == 0)
2217 struct thread_info
*save_thread
= current_thread
;
2219 /* For qSymbol, GDB only changes the current thread if the
2220 previous current thread was of a different process. So if
2221 the previous thread is gone, we need to pick another one of
2222 the same process. This can happen e.g., if we followed an
2223 exec in a non-leader thread. */
2224 if (current_thread
== NULL
)
2227 = find_any_thread_of_pid (cs
.general_thread
.pid ());
2229 /* Just in case, if we didn't find a thread, then bail out
2230 instead of crashing. */
2231 if (current_thread
== NULL
)
2233 write_enn (own_buf
);
2234 current_thread
= save_thread
;
2239 /* GDB is suggesting new symbols have been loaded. This may
2240 mean a new shared library has been detected as loaded, so
2241 take the opportunity to check if breakpoints we think are
2242 inserted, still are. Note that it isn't guaranteed that
2243 we'll see this when a shared library is loaded, and nor will
2244 we see this for unloads (although breakpoints in unloaded
2245 libraries shouldn't trigger), as GDB may not find symbols for
2246 the library at all. We also re-validate breakpoints when we
2247 see a second GDB breakpoint for the same address, and or when
2248 we access breakpoint shadows. */
2249 validate_breakpoints ();
2251 if (target_supports_tracepoints ())
2252 tracepoint_look_up_symbols ();
2254 if (current_thread
!= NULL
)
2255 the_target
->look_up_symbols ();
2257 current_thread
= save_thread
;
2259 strcpy (own_buf
, "OK");
2263 if (!disable_packet_qfThreadInfo
)
2265 if (strcmp ("qfThreadInfo", own_buf
) == 0)
2267 require_running_or_return (own_buf
);
2268 thread_iter
= all_threads
.begin ();
2271 ptid_t ptid
= (*thread_iter
)->id
;
2272 write_ptid (own_buf
, ptid
);
2277 if (strcmp ("qsThreadInfo", own_buf
) == 0)
2279 require_running_or_return (own_buf
);
2280 if (thread_iter
!= all_threads
.end ())
2283 ptid_t ptid
= (*thread_iter
)->id
;
2284 write_ptid (own_buf
, ptid
);
2290 sprintf (own_buf
, "l");
2296 if (the_target
->supports_read_offsets ()
2297 && strcmp ("qOffsets", own_buf
) == 0)
2299 CORE_ADDR text
, data
;
2301 require_running_or_return (own_buf
);
2302 if (the_target
->read_offsets (&text
, &data
))
2303 sprintf (own_buf
, "Text=%lX;Data=%lX;Bss=%lX",
2304 (long)text
, (long)data
, (long)data
);
2306 write_enn (own_buf
);
2311 /* Protocol features query. */
2312 if (startswith (own_buf
, "qSupported")
2313 && (own_buf
[10] == ':' || own_buf
[10] == '\0'))
2315 char *p
= &own_buf
[10];
2316 int gdb_supports_qRelocInsn
= 0;
2318 /* Process each feature being provided by GDB. The first
2319 feature will follow a ':', and latter features will follow
2323 std::vector
<std::string
> qsupported
;
2324 std::vector
<const char *> unknowns
;
2326 /* Two passes, to avoid nested strtok calls in
2327 target_process_qsupported. */
2329 for (p
= strtok_r (p
+ 1, ";", &saveptr
);
2331 p
= strtok_r (NULL
, ";", &saveptr
))
2332 qsupported
.emplace_back (p
);
2334 for (const std::string
&feature
: qsupported
)
2336 if (feature
== "multiprocess+")
2338 /* GDB supports and wants multi-process support if
2340 if (target_supports_multi_process ())
2341 cs
.multi_process
= 1;
2343 else if (feature
== "qRelocInsn+")
2345 /* GDB supports relocate instruction requests. */
2346 gdb_supports_qRelocInsn
= 1;
2348 else if (feature
== "swbreak+")
2350 /* GDB wants us to report whether a trap is caused
2351 by a software breakpoint and for us to handle PC
2352 adjustment if necessary on this target. */
2353 if (target_supports_stopped_by_sw_breakpoint ())
2354 cs
.swbreak_feature
= 1;
2356 else if (feature
== "hwbreak+")
2358 /* GDB wants us to report whether a trap is caused
2359 by a hardware breakpoint. */
2360 if (target_supports_stopped_by_hw_breakpoint ())
2361 cs
.hwbreak_feature
= 1;
2363 else if (feature
== "fork-events+")
2365 /* GDB supports and wants fork events if possible. */
2366 if (target_supports_fork_events ())
2367 cs
.report_fork_events
= 1;
2369 else if (feature
== "vfork-events+")
2371 /* GDB supports and wants vfork events if possible. */
2372 if (target_supports_vfork_events ())
2373 cs
.report_vfork_events
= 1;
2375 else if (feature
== "exec-events+")
2377 /* GDB supports and wants exec events if possible. */
2378 if (target_supports_exec_events ())
2379 cs
.report_exec_events
= 1;
2381 else if (feature
== "vContSupported+")
2382 cs
.vCont_supported
= 1;
2383 else if (feature
== "QThreadEvents+")
2385 else if (feature
== "no-resumed+")
2387 /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
2389 report_no_resumed
= true;
2393 /* Move the unknown features all together. */
2394 unknowns
.push_back (feature
.c_str ());
2398 /* Give the target backend a chance to process the unknown
2400 target_process_qsupported (unknowns
);
2404 "PacketSize=%x;QPassSignals+;QProgramSignals+;"
2405 "QStartupWithShell+;QEnvironmentHexEncoded+;"
2406 "QEnvironmentReset+;QEnvironmentUnset+;"
2410 if (target_supports_catch_syscall ())
2411 strcat (own_buf
, ";QCatchSyscalls+");
2413 if (the_target
->supports_qxfer_libraries_svr4 ())
2414 strcat (own_buf
, ";qXfer:libraries-svr4:read+"
2415 ";augmented-libraries-svr4-read+");
2418 /* We do not have any hook to indicate whether the non-SVR4 target
2419 backend supports qXfer:libraries:read, so always report it. */
2420 strcat (own_buf
, ";qXfer:libraries:read+");
2423 if (the_target
->supports_read_auxv ())
2424 strcat (own_buf
, ";qXfer:auxv:read+");
2426 if (the_target
->supports_qxfer_siginfo ())
2427 strcat (own_buf
, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2429 if (the_target
->supports_read_loadmap ())
2430 strcat (own_buf
, ";qXfer:fdpic:read+");
2432 /* We always report qXfer:features:read, as targets may
2433 install XML files on a subsequent call to arch_setup.
2434 If we reported to GDB on startup that we don't support
2435 qXfer:feature:read at all, we will never be re-queried. */
2436 strcat (own_buf
, ";qXfer:features:read+");
2438 if (cs
.transport_is_reliable
)
2439 strcat (own_buf
, ";QStartNoAckMode+");
2441 if (the_target
->supports_qxfer_osdata ())
2442 strcat (own_buf
, ";qXfer:osdata:read+");
2444 if (target_supports_multi_process ())
2445 strcat (own_buf
, ";multiprocess+");
2447 if (target_supports_fork_events ())
2448 strcat (own_buf
, ";fork-events+");
2450 if (target_supports_vfork_events ())
2451 strcat (own_buf
, ";vfork-events+");
2453 if (target_supports_exec_events ())
2454 strcat (own_buf
, ";exec-events+");
2456 if (target_supports_non_stop ())
2457 strcat (own_buf
, ";QNonStop+");
2459 if (target_supports_disable_randomization ())
2460 strcat (own_buf
, ";QDisableRandomization+");
2462 strcat (own_buf
, ";qXfer:threads:read+");
2464 if (target_supports_tracepoints ())
2466 strcat (own_buf
, ";ConditionalTracepoints+");
2467 strcat (own_buf
, ";TraceStateVariables+");
2468 strcat (own_buf
, ";TracepointSource+");
2469 strcat (own_buf
, ";DisconnectedTracing+");
2470 if (gdb_supports_qRelocInsn
&& target_supports_fast_tracepoints ())
2471 strcat (own_buf
, ";FastTracepoints+");
2472 strcat (own_buf
, ";StaticTracepoints+");
2473 strcat (own_buf
, ";InstallInTrace+");
2474 strcat (own_buf
, ";qXfer:statictrace:read+");
2475 strcat (own_buf
, ";qXfer:traceframe-info:read+");
2476 strcat (own_buf
, ";EnableDisableTracepoints+");
2477 strcat (own_buf
, ";QTBuffer:size+");
2478 strcat (own_buf
, ";tracenz+");
2481 if (target_supports_hardware_single_step ()
2482 || target_supports_software_single_step () )
2484 strcat (own_buf
, ";ConditionalBreakpoints+");
2486 strcat (own_buf
, ";BreakpointCommands+");
2488 if (target_supports_agent ())
2489 strcat (own_buf
, ";QAgent+");
2491 supported_btrace_packets (own_buf
);
2493 if (target_supports_stopped_by_sw_breakpoint ())
2494 strcat (own_buf
, ";swbreak+");
2496 if (target_supports_stopped_by_hw_breakpoint ())
2497 strcat (own_buf
, ";hwbreak+");
2499 if (the_target
->supports_pid_to_exec_file ())
2500 strcat (own_buf
, ";qXfer:exec-file:read+");
2502 strcat (own_buf
, ";vContSupported+");
2504 strcat (own_buf
, ";QThreadEvents+");
2506 strcat (own_buf
, ";no-resumed+");
2508 /* Reinitialize components as needed for the new connection. */
2509 hostio_handle_new_gdb_connection ();
2510 target_handle_new_gdb_connection ();
2515 /* Thread-local storage support. */
2516 if (the_target
->supports_get_tls_address ()
2517 && startswith (own_buf
, "qGetTLSAddr:"))
2519 char *p
= own_buf
+ 12;
2520 CORE_ADDR parts
[2], address
= 0;
2522 ptid_t ptid
= null_ptid
;
2524 require_running_or_return (own_buf
);
2526 for (i
= 0; i
< 3; i
++)
2534 p2
= strchr (p
, ',');
2547 ptid
= read_ptid (p
, NULL
);
2549 decode_address (&parts
[i
- 1], p
, len
);
2553 if (p
!= NULL
|| i
< 3)
2557 struct thread_info
*thread
= find_thread_ptid (ptid
);
2562 err
= the_target
->get_tls_address (thread
, parts
[0], parts
[1],
2568 strcpy (own_buf
, paddress(address
));
2573 write_enn (own_buf
);
2577 /* Otherwise, pretend we do not understand this packet. */
2580 /* Windows OS Thread Information Block address support. */
2581 if (the_target
->supports_get_tib_address ()
2582 && startswith (own_buf
, "qGetTIBAddr:"))
2587 ptid_t ptid
= read_ptid (own_buf
+ 12, &annex
);
2589 n
= the_target
->get_tib_address (ptid
, &tlb
);
2592 strcpy (own_buf
, paddress(tlb
));
2597 write_enn (own_buf
);
2603 /* Handle "monitor" commands. */
2604 if (startswith (own_buf
, "qRcmd,"))
2606 char *mon
= (char *) malloc (PBUFSIZ
);
2607 int len
= strlen (own_buf
+ 6);
2611 write_enn (own_buf
);
2616 || hex2bin (own_buf
+ 6, (gdb_byte
*) mon
, len
/ 2) != len
/ 2)
2618 write_enn (own_buf
);
2622 mon
[len
/ 2] = '\0';
2626 if (the_target
->handle_monitor_command (mon
) == 0)
2627 /* Default processing. */
2628 handle_monitor_command (mon
, own_buf
);
2634 if (startswith (own_buf
, "qSearch:memory:"))
2636 require_running_or_return (own_buf
);
2637 handle_search_memory (own_buf
, packet_len
);
2641 if (strcmp (own_buf
, "qAttached") == 0
2642 || startswith (own_buf
, "qAttached:"))
2644 struct process_info
*process
;
2646 if (own_buf
[sizeof ("qAttached") - 1])
2648 int pid
= strtoul (own_buf
+ sizeof ("qAttached:") - 1, NULL
, 16);
2649 process
= find_process_pid (pid
);
2653 require_running_or_return (own_buf
);
2654 process
= current_process ();
2657 if (process
== NULL
)
2659 write_enn (own_buf
);
2663 strcpy (own_buf
, process
->attached
? "1" : "0");
2667 if (startswith (own_buf
, "qCRC:"))
2669 /* CRC check (compare-section). */
2673 unsigned long long crc
;
2675 require_running_or_return (own_buf
);
2676 comma
= unpack_varlen_hex (own_buf
+ 5, &base
);
2677 if (*comma
++ != ',')
2679 write_enn (own_buf
);
2682 len
= strtoul (comma
, NULL
, 16);
2683 crc
= crc32 (base
, len
, 0xffffffff);
2684 /* Check for memory failure. */
2685 if (crc
== (unsigned long long) -1)
2687 write_enn (own_buf
);
2690 sprintf (own_buf
, "C%lx", (unsigned long) crc
);
2694 if (handle_qxfer (own_buf
, packet_len
, new_packet_len_p
))
2697 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf
))
2700 /* Otherwise we didn't know what packet it was. Say we didn't
2705 static void gdb_wants_all_threads_stopped (void);
2706 static void resume (struct thread_resume
*actions
, size_t n
);
2708 /* The callback that is passed to visit_actioned_threads. */
2709 typedef int (visit_actioned_threads_callback_ftype
)
2710 (const struct thread_resume
*, struct thread_info
*);
2712 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
2713 true if CALLBACK returns true. Returns false if no matching thread
2714 is found or CALLBACK results false.
2715 Note: This function is itself a callback for find_thread. */
2718 visit_actioned_threads (thread_info
*thread
,
2719 const struct thread_resume
*actions
,
2721 visit_actioned_threads_callback_ftype
*callback
)
2723 for (size_t i
= 0; i
< num_actions
; i
++)
2725 const struct thread_resume
*action
= &actions
[i
];
2727 if (action
->thread
== minus_one_ptid
2728 || action
->thread
== thread
->id
2729 || ((action
->thread
.pid ()
2730 == thread
->id
.pid ())
2731 && action
->thread
.lwp () == -1))
2733 if ((*callback
) (action
, thread
))
2741 /* Callback for visit_actioned_threads. If the thread has a pending
2742 status to report, report it now. */
2745 handle_pending_status (const struct thread_resume
*resumption
,
2746 struct thread_info
*thread
)
2748 client_state
&cs
= get_client_state ();
2749 if (thread
->status_pending_p
)
2751 thread
->status_pending_p
= 0;
2753 cs
.last_status
= thread
->last_status
;
2754 cs
.last_ptid
= thread
->id
;
2755 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, &cs
.last_status
);
2761 /* Parse vCont packets. */
2763 handle_v_cont (char *own_buf
)
2767 struct thread_resume
*resume_info
;
2768 struct thread_resume default_action
{ null_ptid
};
2770 /* Count the number of semicolons in the packet. There should be one
2771 for every action. */
2777 p
= strchr (p
, ';');
2780 resume_info
= (struct thread_resume
*) malloc (n
* sizeof (resume_info
[0]));
2781 if (resume_info
== NULL
)
2789 memset (&resume_info
[i
], 0, sizeof resume_info
[i
]);
2791 if (p
[0] == 's' || p
[0] == 'S')
2792 resume_info
[i
].kind
= resume_step
;
2793 else if (p
[0] == 'r')
2794 resume_info
[i
].kind
= resume_step
;
2795 else if (p
[0] == 'c' || p
[0] == 'C')
2796 resume_info
[i
].kind
= resume_continue
;
2797 else if (p
[0] == 't')
2798 resume_info
[i
].kind
= resume_stop
;
2802 if (p
[0] == 'S' || p
[0] == 'C')
2805 int sig
= strtol (p
+ 1, &q
, 16);
2810 if (!gdb_signal_to_host_p ((enum gdb_signal
) sig
))
2812 resume_info
[i
].sig
= gdb_signal_to_host ((enum gdb_signal
) sig
);
2814 else if (p
[0] == 'r')
2818 p
= unpack_varlen_hex (p
+ 1, &addr
);
2819 resume_info
[i
].step_range_start
= addr
;
2824 p
= unpack_varlen_hex (p
+ 1, &addr
);
2825 resume_info
[i
].step_range_end
= addr
;
2834 resume_info
[i
].thread
= minus_one_ptid
;
2835 default_action
= resume_info
[i
];
2837 /* Note: we don't increment i here, we'll overwrite this entry
2838 the next time through. */
2840 else if (p
[0] == ':')
2843 ptid_t ptid
= read_ptid (p
+ 1, &q
);
2848 if (p
[0] != ';' && p
[0] != 0)
2851 resume_info
[i
].thread
= ptid
;
2858 resume_info
[i
] = default_action
;
2860 resume (resume_info
, n
);
2865 write_enn (own_buf
);
2870 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
2873 resume (struct thread_resume
*actions
, size_t num_actions
)
2875 client_state
&cs
= get_client_state ();
2878 /* Check if among the threads that GDB wants actioned, there's
2879 one with a pending status to report. If so, skip actually
2880 resuming/stopping and report the pending event
2883 thread_info
*thread_with_status
= find_thread ([&] (thread_info
*thread
)
2885 return visit_actioned_threads (thread
, actions
, num_actions
,
2886 handle_pending_status
);
2889 if (thread_with_status
!= NULL
)
2895 the_target
->resume (actions
, num_actions
);
2898 write_ok (cs
.own_buf
);
2901 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
, 0, 1);
2903 if (cs
.last_status
.kind
== TARGET_WAITKIND_NO_RESUMED
2904 && !report_no_resumed
)
2906 /* The client does not support this stop reply. At least
2908 sprintf (cs
.own_buf
, "E.No unwaited-for children left.");
2909 disable_async_io ();
2913 if (cs
.last_status
.kind
!= TARGET_WAITKIND_EXITED
2914 && cs
.last_status
.kind
!= TARGET_WAITKIND_SIGNALLED
2915 && cs
.last_status
.kind
!= TARGET_WAITKIND_NO_RESUMED
)
2916 current_thread
->last_status
= cs
.last_status
;
2918 /* From the client's perspective, all-stop mode always stops all
2919 threads implicitly (and the target backend has already done
2920 so by now). Tag all threads as "want-stopped", so we don't
2921 resume them implicitly without the client telling us to. */
2922 gdb_wants_all_threads_stopped ();
2923 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, &cs
.last_status
);
2924 disable_async_io ();
2926 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
2927 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
2928 target_mourn_inferior (cs
.last_ptid
);
2932 /* Attach to a new program. Return 1 if successful, 0 if failure. */
2934 handle_v_attach (char *own_buf
)
2936 client_state
&cs
= get_client_state ();
2939 pid
= strtol (own_buf
+ 8, NULL
, 16);
2940 if (pid
!= 0 && attach_inferior (pid
) == 0)
2942 /* Don't report shared library events after attaching, even if
2943 some libraries are preloaded. GDB will always poll the
2944 library list. Avoids the "stopped by shared library event"
2945 notice on the GDB side. */
2950 /* In non-stop, we don't send a resume reply. Stop events
2951 will follow up using the normal notification
2956 prepare_resume_reply (own_buf
, cs
.last_ptid
, &cs
.last_status
);
2962 write_enn (own_buf
);
2967 /* Run a new program. Return 1 if successful, 0 if failure. */
2969 handle_v_run (char *own_buf
)
2971 client_state
&cs
= get_client_state ();
2973 std::vector
<char *> new_argv
;
2974 char *new_program_name
= NULL
;
2978 for (p
= own_buf
+ strlen ("vRun;"); p
&& *p
; p
= strchr (p
, ';'))
2984 for (i
= 0, p
= own_buf
+ strlen ("vRun;"); *p
; p
= next_p
, ++i
)
2986 next_p
= strchr (p
, ';');
2988 next_p
= p
+ strlen (p
);
2990 if (i
== 0 && p
== next_p
)
2992 /* No program specified. */
2993 new_program_name
= NULL
;
2995 else if (p
== next_p
)
2997 /* Empty argument. */
2998 new_argv
.push_back (xstrdup (""));
3002 size_t len
= (next_p
- p
) / 2;
3003 /* ARG is the unquoted argument received via the RSP. */
3004 char *arg
= (char *) xmalloc (len
+ 1);
3005 /* FULL_ARGS will contain the quoted version of ARG. */
3006 char *full_arg
= (char *) xmalloc ((len
+ 1) * 2);
3007 /* These are pointers used to navigate the strings above. */
3008 char *tmp_arg
= arg
;
3009 char *tmp_full_arg
= full_arg
;
3012 hex2bin (p
, (gdb_byte
*) arg
, len
);
3015 while (*tmp_arg
!= '\0')
3021 *tmp_full_arg
= '\'';
3027 /* Quote single quote. */
3028 *tmp_full_arg
= '\\';
3036 *tmp_full_arg
= *tmp_arg
;
3042 *tmp_full_arg
++ = '\'';
3044 /* Finish FULL_ARG and push it into the vector containing
3046 *tmp_full_arg
= '\0';
3048 new_program_name
= full_arg
;
3050 new_argv
.push_back (full_arg
);
3057 if (new_program_name
== NULL
)
3059 /* GDB didn't specify a program to run. Use the program from the
3060 last run with the new argument list. */
3061 if (program_path
.get () == NULL
)
3063 write_enn (own_buf
);
3064 free_vector_argv (new_argv
);
3069 program_path
.set (gdb::unique_xmalloc_ptr
<char> (new_program_name
));
3071 /* Free the old argv and install the new one. */
3072 free_vector_argv (program_args
);
3073 program_args
= new_argv
;
3075 target_create_inferior (program_path
.get (), program_args
);
3077 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
3079 prepare_resume_reply (own_buf
, cs
.last_ptid
, &cs
.last_status
);
3081 /* In non-stop, sending a resume reply doesn't set the general
3082 thread, but GDB assumes a vRun sets it (this is so GDB can
3083 query which is the main thread of the new inferior. */
3085 cs
.general_thread
= cs
.last_ptid
;
3091 write_enn (own_buf
);
3096 /* Kill process. Return 1 if successful, 0 if failure. */
3098 handle_v_kill (char *own_buf
)
3100 client_state
&cs
= get_client_state ();
3102 char *p
= &own_buf
[6];
3103 if (cs
.multi_process
)
3104 pid
= strtol (p
, NULL
, 16);
3108 process_info
*proc
= find_process_pid (pid
);
3110 if (proc
!= nullptr && kill_inferior (proc
) == 0)
3112 cs
.last_status
.kind
= TARGET_WAITKIND_SIGNALLED
;
3113 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
3114 cs
.last_ptid
= ptid_t (pid
);
3115 discard_queued_stop_replies (cs
.last_ptid
);
3121 write_enn (own_buf
);
3126 /* Handle all of the extended 'v' packets. */
3128 handle_v_requests (char *own_buf
, int packet_len
, int *new_packet_len
)
3130 client_state
&cs
= get_client_state ();
3131 if (!disable_packet_vCont
)
3133 if (strcmp (own_buf
, "vCtrlC") == 0)
3135 the_target
->request_interrupt ();
3140 if (startswith (own_buf
, "vCont;"))
3142 handle_v_cont (own_buf
);
3146 if (startswith (own_buf
, "vCont?"))
3148 strcpy (own_buf
, "vCont;c;C;t");
3150 if (target_supports_hardware_single_step ()
3151 || target_supports_software_single_step ()
3152 || !cs
.vCont_supported
)
3154 /* If target supports single step either by hardware or by
3155 software, add actions s and S to the list of supported
3156 actions. On the other hand, if GDB doesn't request the
3157 supported vCont actions in qSupported packet, add s and
3158 S to the list too. */
3159 own_buf
= own_buf
+ strlen (own_buf
);
3160 strcpy (own_buf
, ";s;S");
3163 if (target_supports_range_stepping ())
3165 own_buf
= own_buf
+ strlen (own_buf
);
3166 strcpy (own_buf
, ";r");
3172 if (startswith (own_buf
, "vFile:")
3173 && handle_vFile (own_buf
, packet_len
, new_packet_len
))
3176 if (startswith (own_buf
, "vAttach;"))
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_attach (own_buf
);
3188 if (startswith (own_buf
, "vRun;"))
3190 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3192 fprintf (stderr
, "Already debugging a process\n");
3193 write_enn (own_buf
);
3196 handle_v_run (own_buf
);
3200 if (startswith (own_buf
, "vKill;"))
3202 if (!target_running ())
3204 fprintf (stderr
, "No process to kill\n");
3205 write_enn (own_buf
);
3208 handle_v_kill (own_buf
);
3212 if (handle_notif_ack (own_buf
, packet_len
))
3215 /* Otherwise we didn't know what packet it was. Say we didn't
3221 /* Resume thread and wait for another event. In non-stop mode,
3222 don't really wait here, but return immediatelly to the event
3225 myresume (char *own_buf
, int step
, int sig
)
3227 client_state
&cs
= get_client_state ();
3228 struct thread_resume resume_info
[2];
3230 int valid_cont_thread
;
3232 valid_cont_thread
= (cs
.cont_thread
!= null_ptid
3233 && cs
.cont_thread
!= minus_one_ptid
);
3235 if (step
|| sig
|| valid_cont_thread
)
3237 resume_info
[0].thread
= current_ptid
;
3239 resume_info
[0].kind
= resume_step
;
3241 resume_info
[0].kind
= resume_continue
;
3242 resume_info
[0].sig
= sig
;
3246 if (!valid_cont_thread
)
3248 resume_info
[n
].thread
= minus_one_ptid
;
3249 resume_info
[n
].kind
= resume_continue
;
3250 resume_info
[n
].sig
= 0;
3254 resume (resume_info
, n
);
3257 /* Callback for for_each_thread. Make a new stop reply for each
3261 queue_stop_reply_callback (thread_info
*thread
)
3263 /* For now, assume targets that don't have this callback also don't
3264 manage the thread's last_status field. */
3265 if (!the_target
->supports_thread_stopped ())
3267 struct vstop_notif
*new_notif
= new struct vstop_notif
;
3269 new_notif
->ptid
= thread
->id
;
3270 new_notif
->status
= thread
->last_status
;
3271 /* Pass the last stop reply back to GDB, but don't notify
3273 notif_event_enque (¬if_stop
, new_notif
);
3277 if (target_thread_stopped (thread
))
3281 std::string status_string
3282 = target_waitstatus_to_string (&thread
->last_status
);
3284 debug_printf ("Reporting thread %s as already stopped with %s\n",
3285 target_pid_to_str (thread
->id
),
3286 status_string
.c_str ());
3289 gdb_assert (thread
->last_status
.kind
!= TARGET_WAITKIND_IGNORE
);
3291 /* Pass the last stop reply back to GDB, but don't notify
3293 queue_stop_reply (thread
->id
, &thread
->last_status
);
3298 /* Set this inferior threads's state as "want-stopped". We won't
3299 resume this thread until the client gives us another action for
3303 gdb_wants_thread_stopped (thread_info
*thread
)
3305 thread
->last_resume_kind
= resume_stop
;
3307 if (thread
->last_status
.kind
== TARGET_WAITKIND_IGNORE
)
3309 /* Most threads are stopped implicitly (all-stop); tag that with
3311 thread
->last_status
.kind
= TARGET_WAITKIND_STOPPED
;
3312 thread
->last_status
.value
.sig
= GDB_SIGNAL_0
;
3316 /* Set all threads' states as "want-stopped". */
3319 gdb_wants_all_threads_stopped (void)
3321 for_each_thread (gdb_wants_thread_stopped
);
3324 /* Callback for for_each_thread. If the thread is stopped with an
3325 interesting event, mark it as having a pending event. */
3328 set_pending_status_callback (thread_info
*thread
)
3330 if (thread
->last_status
.kind
!= TARGET_WAITKIND_STOPPED
3331 || (thread
->last_status
.value
.sig
!= GDB_SIGNAL_0
3332 /* A breakpoint, watchpoint or finished step from a previous
3333 GDB run isn't considered interesting for a new GDB run.
3334 If we left those pending, the new GDB could consider them
3335 random SIGTRAPs. This leaves out real async traps. We'd
3336 have to peek into the (target-specific) siginfo to
3337 distinguish those. */
3338 && thread
->last_status
.value
.sig
!= GDB_SIGNAL_TRAP
))
3339 thread
->status_pending_p
= 1;
3342 /* Status handler for the '?' packet. */
3345 handle_status (char *own_buf
)
3347 client_state
&cs
= get_client_state ();
3349 /* GDB is connected, don't forward events to the target anymore. */
3350 for_each_process ([] (process_info
*process
) {
3351 process
->gdb_detached
= 0;
3354 /* In non-stop mode, we must send a stop reply for each stopped
3355 thread. In all-stop mode, just send one for the first stopped
3360 for_each_thread (queue_stop_reply_callback
);
3362 /* The first is sent immediatly. OK is sent if there is no
3363 stopped thread, which is the same handling of the vStopped
3364 packet (by design). */
3365 notif_write_event (¬if_stop
, cs
.own_buf
);
3369 thread_info
*thread
= NULL
;
3371 target_pause_all (false);
3372 target_stabilize_threads ();
3373 gdb_wants_all_threads_stopped ();
3375 /* We can only report one status, but we might be coming out of
3376 non-stop -- if more than one thread is stopped with
3377 interesting events, leave events for the threads we're not
3378 reporting now pending. They'll be reported the next time the
3379 threads are resumed. Start by marking all interesting events
3381 for_each_thread (set_pending_status_callback
);
3383 /* Prefer the last thread that reported an event to GDB (even if
3384 that was a GDB_SIGNAL_TRAP). */
3385 if (cs
.last_status
.kind
!= TARGET_WAITKIND_IGNORE
3386 && cs
.last_status
.kind
!= TARGET_WAITKIND_EXITED
3387 && cs
.last_status
.kind
!= TARGET_WAITKIND_SIGNALLED
)
3388 thread
= find_thread_ptid (cs
.last_ptid
);
3390 /* If the last event thread is not found for some reason, look
3391 for some other thread that might have an event to report. */
3393 thread
= find_thread ([] (thread_info
*thr_arg
)
3395 return thr_arg
->status_pending_p
;
3398 /* If we're still out of luck, simply pick the first thread in
3401 thread
= get_first_thread ();
3405 struct thread_info
*tp
= (struct thread_info
*) thread
;
3407 /* We're reporting this event, so it's no longer
3409 tp
->status_pending_p
= 0;
3411 /* GDB assumes the current thread is the thread we're
3412 reporting the status for. */
3413 cs
.general_thread
= thread
->id
;
3414 set_desired_thread ();
3416 gdb_assert (tp
->last_status
.kind
!= TARGET_WAITKIND_IGNORE
);
3417 prepare_resume_reply (own_buf
, tp
->id
, &tp
->last_status
);
3420 strcpy (own_buf
, "W00");
3425 gdbserver_version (void)
3427 printf ("GNU gdbserver %s%s\n"
3428 "Copyright (C) 2020 Free Software Foundation, Inc.\n"
3429 "gdbserver is free software, covered by the "
3430 "GNU General Public License.\n"
3431 "This gdbserver was configured as \"%s\"\n",
3432 PKGVERSION
, version
, host_name
);
3436 gdbserver_usage (FILE *stream
)
3438 fprintf (stream
, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3439 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3440 "\tgdbserver [OPTIONS] --multi COMM\n"
3442 "COMM may either be a tty device (for serial debugging),\n"
3443 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3444 "stdin/stdout of gdbserver.\n"
3445 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3446 "PID is the process ID to attach to, when --attach is specified.\n"
3448 "Operating modes:\n"
3450 " --attach Attach to running process PID.\n"
3451 " --multi Start server without a specific program, and\n"
3452 " only quit when explicitly commanded.\n"
3453 " --once Exit after the first connection has closed.\n"
3454 " --help Print this message and then exit.\n"
3455 " --version Display version information and exit.\n"
3459 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3460 " --disable-randomization\n"
3461 " Run PROG with address space randomization disabled.\n"
3462 " --no-disable-randomization\n"
3463 " Don't disable address space randomization when\n"
3465 " --startup-with-shell\n"
3466 " Start PROG using a shell. I.e., execs a shell that\n"
3467 " then execs PROG. (default)\n"
3468 " --no-startup-with-shell\n"
3469 " Exec PROG directly instead of using a shell.\n"
3470 " Disables argument globbing and variable substitution\n"
3471 " on UNIX-like systems.\n"
3475 " --debug Enable general debugging output.\n"
3476 " --debug-format=OPT1[,OPT2,...]\n"
3477 " Specify extra content in debugging output.\n"
3482 " --remote-debug Enable remote protocol debugging output.\n"
3483 " --event-loop-debug Enable event loop debugging output.\n"
3484 " --disable-packet=OPT1[,OPT2,...]\n"
3485 " Disable support for RSP packets or features.\n"
3487 " vCont, Tthread, qC, qfThreadInfo and \n"
3488 " threads (disable all threading packets).\n"
3490 "For more information, consult the GDB manual (available as on-line \n"
3491 "info or a printed manual).\n");
3492 if (REPORT_BUGS_TO
[0] && stream
== stdout
)
3493 fprintf (stream
, "Report bugs to \"%s\".\n", REPORT_BUGS_TO
);
3497 gdbserver_show_disableable (FILE *stream
)
3499 fprintf (stream
, "Disableable packets:\n"
3500 " vCont \tAll vCont packets\n"
3501 " qC \tQuerying the current thread\n"
3502 " qfThreadInfo\tThread listing\n"
3503 " Tthread \tPassing the thread specifier in the "
3504 "T stop reply packet\n"
3505 " threads \tAll of the above\n");
3508 /* Start up the event loop. This is the entry point to the event
3514 /* Loop until there is nothing to do. This is the entry point to
3515 the event loop engine. If nothing is ready at this time, wait
3516 for something to happen (via wait_for_event), then process it.
3517 Return when there are no longer event sources to wait for. */
3519 keep_processing_events
= true;
3520 while (keep_processing_events
)
3522 /* Any events already waiting in the queue? */
3523 int res
= gdb_do_one_event ();
3525 /* Was there an error? */
3530 /* We are done with the event loop. There are no more event sources
3531 to listen to. So we exit gdbserver. */
3535 kill_inferior_callback (process_info
*process
)
3537 kill_inferior (process
);
3538 discard_queued_stop_replies (ptid_t (process
->pid
));
3541 /* Call this when exiting gdbserver with possible inferiors that need
3542 to be killed or detached from. */
3545 detach_or_kill_for_exit (void)
3547 /* First print a list of the inferiors we will be killing/detaching.
3548 This is to assist the user, for example, in case the inferior unexpectedly
3549 dies after we exit: did we screw up or did the inferior exit on its own?
3550 Having this info will save some head-scratching. */
3552 if (have_started_inferiors_p ())
3554 fprintf (stderr
, "Killing process(es):");
3556 for_each_process ([] (process_info
*process
) {
3557 if (!process
->attached
)
3558 fprintf (stderr
, " %d", process
->pid
);
3561 fprintf (stderr
, "\n");
3563 if (have_attached_inferiors_p ())
3565 fprintf (stderr
, "Detaching process(es):");
3567 for_each_process ([] (process_info
*process
) {
3568 if (process
->attached
)
3569 fprintf (stderr
, " %d", process
->pid
);
3572 fprintf (stderr
, "\n");
3575 /* Now we can kill or detach the inferiors. */
3576 for_each_process ([] (process_info
*process
) {
3577 int pid
= process
->pid
;
3579 if (process
->attached
)
3580 detach_inferior (process
);
3582 kill_inferior (process
);
3584 discard_queued_stop_replies (ptid_t (pid
));
3588 /* Value that will be passed to exit(3) when gdbserver exits. */
3589 static int exit_code
;
3591 /* Wrapper for detach_or_kill_for_exit that catches and prints
3595 detach_or_kill_for_exit_cleanup ()
3599 detach_or_kill_for_exit ();
3601 catch (const gdb_exception
&exception
)
3604 fprintf (stderr
, "Detach or kill failed: %s\n",
3610 /* Main function. This is called by the real "main" function,
3611 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
3613 static void ATTRIBUTE_NORETURN
3614 captured_main (int argc
, char *argv
[])
3619 const char *port
= NULL
;
3620 char **next_arg
= &argv
[1];
3621 volatile int multi_mode
= 0;
3622 volatile int attach
= 0;
3624 bool selftest
= false;
3626 std::vector
<const char *> selftest_filters
;
3629 current_directory
= getcwd (NULL
, 0);
3630 client_state
&cs
= get_client_state ();
3632 if (current_directory
== NULL
)
3634 error (_("Could not find current working directory: %s"),
3635 safe_strerror (errno
));
3638 while (*next_arg
!= NULL
&& **next_arg
== '-')
3640 if (strcmp (*next_arg
, "--version") == 0)
3642 gdbserver_version ();
3645 else if (strcmp (*next_arg
, "--help") == 0)
3647 gdbserver_usage (stdout
);
3650 else if (strcmp (*next_arg
, "--attach") == 0)
3652 else if (strcmp (*next_arg
, "--multi") == 0)
3654 else if (strcmp (*next_arg
, "--wrapper") == 0)
3661 while (*next_arg
!= NULL
&& strcmp (*next_arg
, "--") != 0)
3663 wrapper_argv
+= *next_arg
;
3664 wrapper_argv
+= ' ';
3668 if (!wrapper_argv
.empty ())
3670 /* Erase the last whitespace. */
3671 wrapper_argv
.erase (wrapper_argv
.end () - 1);
3674 if (next_arg
== tmp
|| *next_arg
== NULL
)
3676 gdbserver_usage (stderr
);
3680 /* Consume the "--". */
3683 else if (strcmp (*next_arg
, "--debug") == 0)
3685 else if (startswith (*next_arg
, "--debug-format="))
3687 std::string error_msg
3688 = parse_debug_format_options ((*next_arg
)
3689 + sizeof ("--debug-format=") - 1, 0);
3691 if (!error_msg
.empty ())
3693 fprintf (stderr
, "%s", error_msg
.c_str ());
3697 else if (strcmp (*next_arg
, "--remote-debug") == 0)
3699 else if (strcmp (*next_arg
, "--event-loop-debug") == 0)
3700 debug_event_loop
= debug_event_loop_kind::ALL
;
3701 else if (startswith (*next_arg
, "--debug-file="))
3702 debug_set_output ((*next_arg
) + sizeof ("--debug-file=") -1);
3703 else if (strcmp (*next_arg
, "--disable-packet") == 0)
3705 gdbserver_show_disableable (stdout
);
3708 else if (startswith (*next_arg
, "--disable-packet="))
3710 char *packets
= *next_arg
+= sizeof ("--disable-packet=") - 1;
3712 for (char *tok
= strtok_r (packets
, ",", &saveptr
);
3714 tok
= strtok_r (NULL
, ",", &saveptr
))
3716 if (strcmp ("vCont", tok
) == 0)
3717 disable_packet_vCont
= true;
3718 else if (strcmp ("Tthread", tok
) == 0)
3719 disable_packet_Tthread
= true;
3720 else if (strcmp ("qC", tok
) == 0)
3721 disable_packet_qC
= true;
3722 else if (strcmp ("qfThreadInfo", tok
) == 0)
3723 disable_packet_qfThreadInfo
= true;
3724 else if (strcmp ("T", tok
) == 0)
3725 disable_packet_T
= true;
3726 else if (strcmp ("threads", tok
) == 0)
3728 disable_packet_vCont
= true;
3729 disable_packet_Tthread
= true;
3730 disable_packet_qC
= true;
3731 disable_packet_qfThreadInfo
= true;
3735 fprintf (stderr
, "Don't know how to disable \"%s\".\n\n",
3737 gdbserver_show_disableable (stderr
);
3742 else if (strcmp (*next_arg
, "-") == 0)
3744 /* "-" specifies a stdio connection and is a form of port
3746 port
= STDIO_CONNECTION_NAME
;
3750 else if (strcmp (*next_arg
, "--disable-randomization") == 0)
3751 cs
.disable_randomization
= 1;
3752 else if (strcmp (*next_arg
, "--no-disable-randomization") == 0)
3753 cs
.disable_randomization
= 0;
3754 else if (strcmp (*next_arg
, "--startup-with-shell") == 0)
3755 startup_with_shell
= true;
3756 else if (strcmp (*next_arg
, "--no-startup-with-shell") == 0)
3757 startup_with_shell
= false;
3758 else if (strcmp (*next_arg
, "--once") == 0)
3760 else if (strcmp (*next_arg
, "--selftest") == 0)
3762 else if (startswith (*next_arg
, "--selftest="))
3767 const char *filter
= *next_arg
+ strlen ("--selftest=");
3768 if (*filter
== '\0')
3770 fprintf (stderr
, _("Error: selftest filter is empty.\n"));
3774 selftest_filters
.push_back (filter
);
3779 fprintf (stderr
, "Unknown argument: %s\n", *next_arg
);
3792 if ((port
== NULL
|| (!attach
&& !multi_mode
&& *next_arg
== NULL
))
3795 gdbserver_usage (stderr
);
3799 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
3800 opened by remote_prepare. */
3803 save_original_signals_state (false);
3805 /* We need to know whether the remote connection is stdio before
3806 starting the inferior. Inferiors created in this scenario have
3807 stdin,stdout redirected. So do this here before we call
3810 remote_prepare (port
);
3815 /* --attach used to come after PORT, so allow it there for
3817 if (*next_arg
!= NULL
&& strcmp (*next_arg
, "--attach") == 0)
3824 && (*next_arg
== NULL
3825 || (*next_arg
)[0] == '\0'
3826 || (pid
= strtoul (*next_arg
, &arg_end
, 0)) == 0
3828 || next_arg
[1] != NULL
))
3833 gdbserver_usage (stderr
);
3837 /* Gather information about the environment. */
3838 our_environ
= gdb_environ::from_host_environ ();
3840 initialize_async_io ();
3842 have_job_control ();
3843 if (target_supports_tracepoints ())
3844 initialize_tracepoint ();
3846 mem_buf
= (unsigned char *) xmalloc (PBUFSIZ
);
3851 selftests::run_tests (selftest_filters
);
3853 printf (_("Selftests have been disabled for this build.\n"));
3855 throw_quit ("Quit");
3858 if (pid
== 0 && *next_arg
!= NULL
)
3862 n
= argc
- (next_arg
- argv
);
3863 program_path
.set (make_unique_xstrdup (next_arg
[0]));
3864 for (i
= 1; i
< n
; i
++)
3865 program_args
.push_back (xstrdup (next_arg
[i
]));
3867 /* Wait till we are at first instruction in program. */
3868 target_create_inferior (program_path
.get (), program_args
);
3870 /* We are now (hopefully) stopped at the first instruction of
3871 the target process. This assumes that the target process was
3872 successfully created. */
3876 if (attach_inferior (pid
) == -1)
3877 error ("Attaching not supported on this target");
3879 /* Otherwise succeeded. */
3883 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
3884 cs
.last_status
.value
.integer
= 0;
3885 cs
.last_ptid
= minus_one_ptid
;
3888 SCOPE_EXIT
{ detach_or_kill_for_exit_cleanup (); };
3890 /* Don't report shared library events on the initial connection,
3891 even if some libraries are preloaded. Avoids the "stopped by
3892 shared library event" notice on gdb side. */
3895 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
3896 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
3901 if (!was_running
&& !multi_mode
)
3902 error ("No program to debug");
3907 cs
.multi_process
= 0;
3908 cs
.report_fork_events
= 0;
3909 cs
.report_vfork_events
= 0;
3910 cs
.report_exec_events
= 0;
3911 /* Be sure we're out of tfind mode. */
3912 cs
.current_traceframe
= -1;
3913 cs
.cont_thread
= null_ptid
;
3914 cs
.swbreak_feature
= 0;
3915 cs
.hwbreak_feature
= 0;
3916 cs
.vCont_supported
= 0;
3922 /* Wait for events. This will return when all event sources
3923 are removed from the event loop. */
3924 start_event_loop ();
3926 /* If an exit was requested (using the "monitor exit"
3927 command), terminate now. */
3929 throw_quit ("Quit");
3931 /* The only other way to get here is for getpkt to fail:
3933 - If --once was specified, we're done.
3935 - If not in extended-remote mode, and we're no longer
3936 debugging anything, simply exit: GDB has disconnected
3937 after processing the last process exit.
3939 - Otherwise, close the connection and reopen it at the
3941 if (run_once
|| (!extended_protocol
&& !target_running ()))
3942 throw_quit ("Quit");
3945 "Remote side has terminated connection. "
3946 "GDBserver will reopen the connection.\n");
3948 /* Get rid of any pending statuses. An eventual reconnection
3949 (by the same GDB instance or another) will refresh all its
3950 state from scratch. */
3951 discard_queued_stop_replies (minus_one_ptid
);
3952 for_each_thread ([] (thread_info
*thread
)
3954 thread
->status_pending_p
= 0;
3959 if (disconnected_tracing
)
3961 /* Try to enable non-stop/async mode, so we we can
3962 both wait for an async socket accept, and handle
3963 async target events simultaneously. There's also
3964 no point either in having the target always stop
3965 all threads, when we're going to pass signals
3966 down without informing GDB. */
3969 if (the_target
->start_non_stop (true))
3972 /* Detaching implicitly resumes all threads;
3973 simply disconnecting does not. */
3979 "Disconnected tracing disabled; "
3980 "stopping trace run.\n");
3985 catch (const gdb_exception_error
&exception
)
3988 fprintf (stderr
, "gdbserver: %s\n", exception
.what ());
3990 if (response_needed
)
3992 write_enn (cs
.own_buf
);
3993 putpkt (cs
.own_buf
);
3997 throw_quit ("Quit");
4002 /* Main function. */
4005 main (int argc
, char *argv
[])
4010 captured_main (argc
, argv
);
4012 catch (const gdb_exception
&exception
)
4014 if (exception
.reason
== RETURN_ERROR
)
4017 fprintf (stderr
, "%s\n", exception
.what ());
4018 fprintf (stderr
, "Exiting\n");
4025 gdb_assert_not_reached ("captured_main should never return");
4028 /* Process options coming from Z packets for a breakpoint. PACKET is
4029 the packet buffer. *PACKET is updated to point to the first char
4030 after the last processed option. */
4033 process_point_options (struct gdb_breakpoint
*bp
, const char **packet
)
4035 const char *dataptr
= *packet
;
4038 /* Check if data has the correct format. */
4039 if (*dataptr
!= ';')
4046 if (*dataptr
== ';')
4049 if (*dataptr
== 'X')
4051 /* Conditional expression. */
4053 debug_printf ("Found breakpoint condition.\n");
4054 if (!add_breakpoint_condition (bp
, &dataptr
))
4055 dataptr
= strchrnul (dataptr
, ';');
4057 else if (startswith (dataptr
, "cmds:"))
4059 dataptr
+= strlen ("cmds:");
4061 debug_printf ("Found breakpoint commands %s.\n", dataptr
);
4062 persist
= (*dataptr
== '1');
4064 if (add_breakpoint_commands (bp
, &dataptr
, persist
))
4065 dataptr
= strchrnul (dataptr
, ';');
4069 fprintf (stderr
, "Unknown token %c, ignoring.\n",
4071 /* Skip tokens until we find one that we recognize. */
4072 dataptr
= strchrnul (dataptr
, ';');
4078 /* Event loop callback that handles a serial event. The first byte in
4079 the serial buffer gets us here. We expect characters to arrive at
4080 a brisk pace, so we read the rest of the packet with a blocking
4084 process_serial_event (void)
4086 client_state
&cs
= get_client_state ();
4092 int new_packet_len
= -1;
4094 disable_async_io ();
4096 response_needed
= false;
4097 packet_len
= getpkt (cs
.own_buf
);
4098 if (packet_len
<= 0)
4101 /* Force an event loop break. */
4104 response_needed
= true;
4106 char ch
= cs
.own_buf
[0];
4110 handle_query (cs
.own_buf
, packet_len
, &new_packet_len
);
4113 handle_general_set (cs
.own_buf
);
4116 handle_detach (cs
.own_buf
);
4119 extended_protocol
= true;
4120 write_ok (cs
.own_buf
);
4123 handle_status (cs
.own_buf
);
4126 if (cs
.own_buf
[1] == 'c' || cs
.own_buf
[1] == 'g' || cs
.own_buf
[1] == 's')
4128 require_running_or_break (cs
.own_buf
);
4130 ptid_t thread_id
= read_ptid (&cs
.own_buf
[2], NULL
);
4132 if (thread_id
== null_ptid
|| thread_id
== minus_one_ptid
)
4133 thread_id
= null_ptid
;
4134 else if (thread_id
.is_pid ())
4136 /* The ptid represents a pid. */
4137 thread_info
*thread
= find_any_thread_of_pid (thread_id
.pid ());
4141 write_enn (cs
.own_buf
);
4145 thread_id
= thread
->id
;
4149 /* The ptid represents a lwp/tid. */
4150 if (find_thread_ptid (thread_id
) == NULL
)
4152 write_enn (cs
.own_buf
);
4157 if (cs
.own_buf
[1] == 'g')
4159 if (thread_id
== null_ptid
)
4161 /* GDB is telling us to choose any thread. Check if
4162 the currently selected thread is still valid. If
4163 it is not, select the first available. */
4164 thread_info
*thread
= find_thread_ptid (cs
.general_thread
);
4166 thread
= get_first_thread ();
4167 thread_id
= thread
->id
;
4170 cs
.general_thread
= thread_id
;
4171 set_desired_thread ();
4172 gdb_assert (current_thread
!= NULL
);
4174 else if (cs
.own_buf
[1] == 'c')
4175 cs
.cont_thread
= thread_id
;
4177 write_ok (cs
.own_buf
);
4181 /* Silently ignore it so that gdb can extend the protocol
4182 without compatibility headaches. */
4183 cs
.own_buf
[0] = '\0';
4187 require_running_or_break (cs
.own_buf
);
4188 if (cs
.current_traceframe
>= 0)
4190 struct regcache
*regcache
4191 = new_register_cache (current_target_desc ());
4193 if (fetch_traceframe_registers (cs
.current_traceframe
,
4195 registers_to_string (regcache
, cs
.own_buf
);
4197 write_enn (cs
.own_buf
);
4198 free_register_cache (regcache
);
4202 struct regcache
*regcache
;
4204 if (!set_desired_thread ())
4205 write_enn (cs
.own_buf
);
4208 regcache
= get_thread_regcache (current_thread
, 1);
4209 registers_to_string (regcache
, cs
.own_buf
);
4214 require_running_or_break (cs
.own_buf
);
4215 if (cs
.current_traceframe
>= 0)
4216 write_enn (cs
.own_buf
);
4219 struct regcache
*regcache
;
4221 if (!set_desired_thread ())
4222 write_enn (cs
.own_buf
);
4225 regcache
= get_thread_regcache (current_thread
, 1);
4226 registers_from_string (regcache
, &cs
.own_buf
[1]);
4227 write_ok (cs
.own_buf
);
4233 require_running_or_break (cs
.own_buf
);
4234 decode_m_packet (&cs
.own_buf
[1], &mem_addr
, &len
);
4235 int res
= gdb_read_memory (mem_addr
, mem_buf
, len
);
4237 write_enn (cs
.own_buf
);
4239 bin2hex (mem_buf
, cs
.own_buf
, res
);
4243 require_running_or_break (cs
.own_buf
);
4244 decode_M_packet (&cs
.own_buf
[1], &mem_addr
, &len
, &mem_buf
);
4245 if (gdb_write_memory (mem_addr
, mem_buf
, len
) == 0)
4246 write_ok (cs
.own_buf
);
4248 write_enn (cs
.own_buf
);
4251 require_running_or_break (cs
.own_buf
);
4252 if (decode_X_packet (&cs
.own_buf
[1], packet_len
- 1,
4253 &mem_addr
, &len
, &mem_buf
) < 0
4254 || gdb_write_memory (mem_addr
, mem_buf
, len
) != 0)
4255 write_enn (cs
.own_buf
);
4257 write_ok (cs
.own_buf
);
4260 require_running_or_break (cs
.own_buf
);
4261 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4262 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4263 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4266 myresume (cs
.own_buf
, 0, signal
);
4269 require_running_or_break (cs
.own_buf
);
4270 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4271 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4272 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4275 myresume (cs
.own_buf
, 1, signal
);
4278 require_running_or_break (cs
.own_buf
);
4280 myresume (cs
.own_buf
, 0, signal
);
4283 require_running_or_break (cs
.own_buf
);
4285 myresume (cs
.own_buf
, 1, signal
);
4287 case 'Z': /* insert_ ... */
4289 case 'z': /* remove_ ... */
4294 char type
= cs
.own_buf
[1];
4296 const int insert
= ch
== 'Z';
4297 const char *p
= &cs
.own_buf
[3];
4299 p
= unpack_varlen_hex (p
, &addr
);
4300 kind
= strtol (p
+ 1, &dataptr
, 16);
4304 struct gdb_breakpoint
*bp
;
4306 bp
= set_gdb_breakpoint (type
, addr
, kind
, &res
);
4311 /* GDB may have sent us a list of *point parameters to
4312 be evaluated on the target's side. Read such list
4313 here. If we already have a list of parameters, GDB
4314 is telling us to drop that list and use this one
4316 clear_breakpoint_conditions_and_commands (bp
);
4317 const char *options
= dataptr
;
4318 process_point_options (bp
, &options
);
4322 res
= delete_gdb_breakpoint (type
, addr
, kind
);
4325 write_ok (cs
.own_buf
);
4328 cs
.own_buf
[0] = '\0';
4330 write_enn (cs
.own_buf
);
4334 response_needed
= false;
4335 if (!target_running ())
4336 /* The packet we received doesn't make sense - but we can't
4337 reply to it, either. */
4340 fprintf (stderr
, "Killing all inferiors\n");
4342 for_each_process (kill_inferior_callback
);
4344 /* When using the extended protocol, we wait with no program
4345 running. The traditional protocol will exit instead. */
4346 if (extended_protocol
)
4348 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
4349 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
4357 require_running_or_break (cs
.own_buf
);
4359 ptid_t thread_id
= read_ptid (&cs
.own_buf
[1], NULL
);
4360 if (find_thread_ptid (thread_id
) == NULL
)
4362 write_enn (cs
.own_buf
);
4366 if (mythread_alive (thread_id
))
4367 write_ok (cs
.own_buf
);
4369 write_enn (cs
.own_buf
);
4373 response_needed
= false;
4375 /* Restarting the inferior is only supported in the extended
4377 if (extended_protocol
)
4379 if (target_running ())
4380 for_each_process (kill_inferior_callback
);
4382 fprintf (stderr
, "GDBserver restarting\n");
4384 /* Wait till we are at 1st instruction in prog. */
4385 if (program_path
.get () != NULL
)
4387 target_create_inferior (program_path
.get (), program_args
);
4389 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
4391 /* Stopped at the first instruction of the target
4393 cs
.general_thread
= cs
.last_ptid
;
4397 /* Something went wrong. */
4398 cs
.general_thread
= null_ptid
;
4403 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
4404 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
4410 /* It is a request we don't understand. Respond with an
4411 empty packet so that gdb knows that we don't support this
4413 cs
.own_buf
[0] = '\0';
4417 /* Extended (long) request. */
4418 handle_v_requests (cs
.own_buf
, packet_len
, &new_packet_len
);
4422 /* It is a request we don't understand. Respond with an empty
4423 packet so that gdb knows that we don't support this
4425 cs
.own_buf
[0] = '\0';
4429 if (new_packet_len
!= -1)
4430 putpkt_binary (cs
.own_buf
, new_packet_len
);
4432 putpkt (cs
.own_buf
);
4434 response_needed
= false;
4442 /* Event-loop callback for serial events. */
4445 handle_serial_event (int err
, gdb_client_data client_data
)
4448 debug_printf ("handling possible serial event\n");
4450 /* Really handle it. */
4451 if (process_serial_event () < 0)
4453 keep_processing_events
= false;
4457 /* Be sure to not change the selected thread behind GDB's back.
4458 Important in the non-stop mode asynchronous protocol. */
4459 set_desired_thread ();
4462 /* Push a stop notification on the notification queue. */
4465 push_stop_notification (ptid_t ptid
, struct target_waitstatus
*status
)
4467 struct vstop_notif
*vstop_notif
= new struct vstop_notif
;
4469 vstop_notif
->status
= *status
;
4470 vstop_notif
->ptid
= ptid
;
4471 /* Push Stop notification. */
4472 notif_push (¬if_stop
, vstop_notif
);
4475 /* Event-loop callback for target events. */
4478 handle_target_event (int err
, gdb_client_data client_data
)
4480 client_state
&cs
= get_client_state ();
4482 debug_printf ("handling possible target event\n");
4484 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
,
4487 if (cs
.last_status
.kind
== TARGET_WAITKIND_NO_RESUMED
)
4489 if (gdb_connected () && report_no_resumed
)
4490 push_stop_notification (null_ptid
, &cs
.last_status
);
4492 else if (cs
.last_status
.kind
!= TARGET_WAITKIND_IGNORE
)
4494 int pid
= cs
.last_ptid
.pid ();
4495 struct process_info
*process
= find_process_pid (pid
);
4496 int forward_event
= !gdb_connected () || process
->gdb_detached
;
4498 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
4499 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
4501 mark_breakpoints_out (process
);
4502 target_mourn_inferior (cs
.last_ptid
);
4504 else if (cs
.last_status
.kind
== TARGET_WAITKIND_THREAD_EXITED
)
4508 /* We're reporting this thread as stopped. Update its
4509 "want-stopped" state to what the client wants, until it
4510 gets a new resume action. */
4511 current_thread
->last_resume_kind
= resume_stop
;
4512 current_thread
->last_status
= cs
.last_status
;
4517 if (!target_running ())
4519 /* The last process exited. We're done. */
4523 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
4524 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
4525 || cs
.last_status
.kind
== TARGET_WAITKIND_THREAD_EXITED
)
4529 /* A thread stopped with a signal, but gdb isn't
4530 connected to handle it. Pass it down to the
4531 inferior, as if it wasn't being traced. */
4532 enum gdb_signal signal
;
4535 debug_printf ("GDB not connected; forwarding event %d for"
4537 (int) cs
.last_status
.kind
,
4538 target_pid_to_str (cs
.last_ptid
));
4540 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
4541 signal
= cs
.last_status
.value
.sig
;
4543 signal
= GDB_SIGNAL_0
;
4544 target_continue (cs
.last_ptid
, signal
);
4548 push_stop_notification (cs
.last_ptid
, &cs
.last_status
);
4551 /* Be sure to not change the selected thread behind GDB's back.
4552 Important in the non-stop mode asynchronous protocol. */
4553 set_desired_thread ();
4556 /* See gdbsupport/event-loop.h. */
4559 invoke_async_signal_handlers ()
4564 /* See gdbsupport/event-loop.h. */
4567 check_async_event_handlers ()
4572 /* See gdbsupport/errors.h */
4581 /* See gdbsupport/gdb_select.h. */
4584 gdb_select (int n
, fd_set
*readfds
, fd_set
*writefds
,
4585 fd_set
*exceptfds
, struct timeval
*timeout
)
4587 return select (n
, readfds
, writefds
, exceptfds
, timeout
);
4598 } // namespace selftests
4599 #endif /* GDB_SELF_TEST */