1 /* Main code for remote server for GDB.
2 Copyright (C) 1989-2019 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 "gdbsupport/selftest.h"
46 #include "gdbsupport/scope-exit.h"
48 #define require_running_or_return(BUF) \
49 if (!target_running ()) \
55 #define require_running_or_break(BUF) \
56 if (!target_running ()) \
62 /* String containing the current directory (what getwd would return). */
64 char *current_directory
;
66 /* The environment to pass to the inferior when creating it. */
68 static gdb_environ our_environ
;
70 /* Start the inferior using a shell. */
72 /* We always try to start the inferior using a shell. */
74 int startup_with_shell
= 1;
78 static int extended_protocol
;
79 static int response_needed
;
80 static int exit_requested
;
82 /* --once: Exit after the first connection has closed. */
85 /* Whether to report TARGET_WAITKING_NO_RESUMED events. */
86 static int report_no_resumed
;
91 /* Set the PROGRAM_PATH. Here we adjust the path of the provided
93 void set (gdb::unique_xmalloc_ptr
<char> &&path
)
95 m_path
= std::move (path
);
97 /* Make sure we're using the absolute path of the inferior when
99 if (!contains_dir_separator (m_path
.get ()))
103 /* Check if the file is in our CWD. If it is, then we prefix
104 its name with CURRENT_DIRECTORY. Otherwise, we leave the
105 name as-is because we'll try searching for it in $PATH. */
106 if (is_regular_file (m_path
.get (), ®_file_errno
))
107 m_path
= gdb_abspath (m_path
.get ());
111 /* Return the PROGRAM_PATH. */
113 { return m_path
.get (); }
116 /* The program name, adjusted if needed. */
117 gdb::unique_xmalloc_ptr
<char> m_path
;
119 static std::vector
<char *> program_args
;
120 static std::string wrapper_argv
;
122 /* The PID of the originally created or attached inferior. Used to
123 send signals to the process when GDB sends us an asynchronous interrupt
124 (user hitting Control-C in the client), and to wait for the child to exit
125 when no longer debugging it. */
127 unsigned long signal_pid
;
129 /* Set if you want to disable optional thread related packets support
130 in gdbserver, for the sake of testing GDB against stubs that don't
132 int disable_packet_vCont
;
133 int disable_packet_Tthread
;
134 int disable_packet_qC
;
135 int disable_packet_qfThreadInfo
;
137 static unsigned char *mem_buf
;
139 /* A sub-class of 'struct notif_event' for stop, holding information
140 relative to a single stop reply. We keep a queue of these to
141 push to GDB in non-stop mode. */
143 struct vstop_notif
: public notif_event
145 /* Thread or process that got the event. */
149 struct target_waitstatus status
;
152 /* The current btrace configuration. This is gdbserver's mirror of GDB's
153 btrace configuration. */
154 static struct btrace_config current_btrace_conf
;
156 /* The client remote protocol state. */
158 static client_state g_client_state
;
163 client_state
&cs
= g_client_state
;
168 /* Put a stop reply to the stop reply queue. */
171 queue_stop_reply (ptid_t ptid
, struct target_waitstatus
*status
)
173 struct vstop_notif
*new_notif
= new struct vstop_notif
;
175 new_notif
->ptid
= ptid
;
176 new_notif
->status
= *status
;
178 notif_event_enque (¬if_stop
, new_notif
);
182 remove_all_on_match_ptid (struct notif_event
*event
, ptid_t filter_ptid
)
184 struct vstop_notif
*vstop_event
= (struct vstop_notif
*) event
;
186 return vstop_event
->ptid
.matches (filter_ptid
);
192 discard_queued_stop_replies (ptid_t ptid
)
194 std::list
<notif_event
*>::iterator iter
, next
, end
;
195 end
= notif_stop
.queue
.end ();
196 for (iter
= notif_stop
.queue
.begin (); iter
!= end
; iter
= next
)
201 if (remove_all_on_match_ptid (*iter
, ptid
))
204 notif_stop
.queue
.erase (iter
);
210 vstop_notif_reply (struct notif_event
*event
, char *own_buf
)
212 struct vstop_notif
*vstop
= (struct vstop_notif
*) event
;
214 prepare_resume_reply (own_buf
, vstop
->ptid
, &vstop
->status
);
217 /* Helper for in_queued_stop_replies. */
220 in_queued_stop_replies_ptid (struct notif_event
*event
, ptid_t filter_ptid
)
222 struct vstop_notif
*vstop_event
= (struct vstop_notif
*) event
;
224 if (vstop_event
->ptid
.matches (filter_ptid
))
227 /* Don't resume fork children that GDB does not know about yet. */
228 if ((vstop_event
->status
.kind
== TARGET_WAITKIND_FORKED
229 || vstop_event
->status
.kind
== TARGET_WAITKIND_VFORKED
)
230 && vstop_event
->status
.value
.related_pid
.matches (filter_ptid
))
239 in_queued_stop_replies (ptid_t ptid
)
241 for (notif_event
*event
: notif_stop
.queue
)
243 if (in_queued_stop_replies_ptid (event
, ptid
))
250 struct notif_server notif_stop
=
252 "vStopped", "Stop", {}, vstop_notif_reply
,
256 target_running (void)
258 return get_first_thread () != NULL
;
261 /* See gdbsupport/common-inferior.h. */
266 return !wrapper_argv
.empty () ? wrapper_argv
.c_str () : NULL
;
269 /* See gdbsupport/common-inferior.h. */
272 get_exec_file (int err
)
274 if (err
&& program_path
.get () == NULL
)
275 error (_("No executable file specified."));
277 return program_path
.get ();
289 attach_inferior (int pid
)
291 client_state
&cs
= get_client_state ();
292 /* myattach should return -1 if attaching is unsupported,
293 0 if it succeeded, and call error() otherwise. */
295 if (find_process_pid (pid
) != nullptr)
296 error ("Already attached to process %d\n", pid
);
298 if (myattach (pid
) != 0)
301 fprintf (stderr
, "Attached; pid = %d\n", pid
);
304 /* FIXME - It may be that we should get the SIGNAL_PID from the
305 attach function, so that it can be the main thread instead of
306 whichever we were told to attach to. */
311 cs
.last_ptid
= mywait (ptid_t (pid
), &cs
.last_status
, 0, 0);
313 /* GDB knows to ignore the first SIGSTOP after attaching to a running
314 process using the "attach" command, but this is different; it's
315 just using "target remote". Pretend it's just starting up. */
316 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
317 && cs
.last_status
.value
.sig
== GDB_SIGNAL_STOP
)
318 cs
.last_status
.value
.sig
= GDB_SIGNAL_TRAP
;
320 current_thread
->last_resume_kind
= resume_stop
;
321 current_thread
->last_status
= cs
.last_status
;
327 /* Decode a qXfer read request. Return 0 if everything looks OK,
331 decode_xfer_read (char *buf
, CORE_ADDR
*ofs
, unsigned int *len
)
333 /* After the read marker and annex, qXfer looks like a
334 traditional 'm' packet. */
335 decode_m_packet (buf
, ofs
, len
);
341 decode_xfer (char *buf
, char **object
, char **rw
, char **annex
, char **offset
)
343 /* Extract and NUL-terminate the object. */
345 while (*buf
&& *buf
!= ':')
351 /* Extract and NUL-terminate the read/write action. */
353 while (*buf
&& *buf
!= ':')
359 /* Extract and NUL-terminate the annex. */
361 while (*buf
&& *buf
!= ':')
371 /* Write the response to a successful qXfer read. Returns the
372 length of the (binary) data stored in BUF, corresponding
373 to as much of DATA/LEN as we could fit. IS_MORE controls
374 the first character of the response. */
376 write_qxfer_response (char *buf
, const gdb_byte
*data
, int len
, int is_more
)
385 return remote_escape_output (data
, len
, 1, (unsigned char *) buf
+ 1,
386 &out_len
, PBUFSIZ
- 2) + 1;
389 /* Handle btrace enabling in BTS format. */
392 handle_btrace_enable_bts (struct thread_info
*thread
)
394 if (thread
->btrace
!= NULL
)
395 error (_("Btrace already enabled."));
397 current_btrace_conf
.format
= BTRACE_FORMAT_BTS
;
398 thread
->btrace
= target_enable_btrace (thread
->id
, ¤t_btrace_conf
);
401 /* Handle btrace enabling in Intel Processor Trace format. */
404 handle_btrace_enable_pt (struct thread_info
*thread
)
406 if (thread
->btrace
!= NULL
)
407 error (_("Btrace already enabled."));
409 current_btrace_conf
.format
= BTRACE_FORMAT_PT
;
410 thread
->btrace
= target_enable_btrace (thread
->id
, ¤t_btrace_conf
);
413 /* Handle btrace disabling. */
416 handle_btrace_disable (struct thread_info
*thread
)
419 if (thread
->btrace
== NULL
)
420 error (_("Branch tracing not enabled."));
422 if (target_disable_btrace (thread
->btrace
) != 0)
423 error (_("Could not disable branch tracing."));
425 thread
->btrace
= NULL
;
428 /* Handle the "Qbtrace" packet. */
431 handle_btrace_general_set (char *own_buf
)
433 client_state
&cs
= get_client_state ();
434 struct thread_info
*thread
;
437 if (!startswith (own_buf
, "Qbtrace:"))
440 op
= own_buf
+ strlen ("Qbtrace:");
442 if (cs
.general_thread
== null_ptid
443 || cs
.general_thread
== minus_one_ptid
)
445 strcpy (own_buf
, "E.Must select a single thread.");
449 thread
= find_thread_ptid (cs
.general_thread
);
452 strcpy (own_buf
, "E.No such thread.");
458 if (strcmp (op
, "bts") == 0)
459 handle_btrace_enable_bts (thread
);
460 else if (strcmp (op
, "pt") == 0)
461 handle_btrace_enable_pt (thread
);
462 else if (strcmp (op
, "off") == 0)
463 handle_btrace_disable (thread
);
465 error (_("Bad Qbtrace operation. Use bts, pt, or off."));
469 catch (const gdb_exception_error
&exception
)
471 sprintf (own_buf
, "E.%s", exception
.what ());
477 /* Handle the "Qbtrace-conf" packet. */
480 handle_btrace_conf_general_set (char *own_buf
)
482 client_state
&cs
= get_client_state ();
483 struct thread_info
*thread
;
486 if (!startswith (own_buf
, "Qbtrace-conf:"))
489 op
= own_buf
+ strlen ("Qbtrace-conf:");
491 if (cs
.general_thread
== null_ptid
492 || cs
.general_thread
== minus_one_ptid
)
494 strcpy (own_buf
, "E.Must select a single thread.");
498 thread
= find_thread_ptid (cs
.general_thread
);
501 strcpy (own_buf
, "E.No such thread.");
505 if (startswith (op
, "bts:size="))
511 size
= strtoul (op
+ strlen ("bts:size="), &endp
, 16);
512 if (endp
== NULL
|| *endp
!= 0 || errno
!= 0 || size
> UINT_MAX
)
514 strcpy (own_buf
, "E.Bad size value.");
518 current_btrace_conf
.bts
.size
= (unsigned int) size
;
520 else if (strncmp (op
, "pt:size=", strlen ("pt:size=")) == 0)
526 size
= strtoul (op
+ strlen ("pt:size="), &endp
, 16);
527 if (endp
== NULL
|| *endp
!= 0 || errno
!= 0 || size
> UINT_MAX
)
529 strcpy (own_buf
, "E.Bad size value.");
533 current_btrace_conf
.pt
.size
= (unsigned int) size
;
537 strcpy (own_buf
, "E.Bad Qbtrace configuration option.");
545 /* Handle all of the extended 'Q' packets. */
548 handle_general_set (char *own_buf
)
550 client_state
&cs
= get_client_state ();
551 if (startswith (own_buf
, "QPassSignals:"))
553 int numsigs
= (int) GDB_SIGNAL_LAST
, i
;
554 const char *p
= own_buf
+ strlen ("QPassSignals:");
557 p
= decode_address_to_semicolon (&cursig
, p
);
558 for (i
= 0; i
< numsigs
; i
++)
562 cs
.pass_signals
[i
] = 1;
564 /* Keep looping, to clear the remaining signals. */
567 p
= decode_address_to_semicolon (&cursig
, p
);
570 cs
.pass_signals
[i
] = 0;
572 strcpy (own_buf
, "OK");
576 if (startswith (own_buf
, "QProgramSignals:"))
578 int numsigs
= (int) GDB_SIGNAL_LAST
, i
;
579 const char *p
= own_buf
+ strlen ("QProgramSignals:");
582 cs
.program_signals_p
= 1;
584 p
= decode_address_to_semicolon (&cursig
, p
);
585 for (i
= 0; i
< numsigs
; i
++)
589 cs
.program_signals
[i
] = 1;
591 /* Keep looping, to clear the remaining signals. */
594 p
= decode_address_to_semicolon (&cursig
, p
);
597 cs
.program_signals
[i
] = 0;
599 strcpy (own_buf
, "OK");
603 if (startswith (own_buf
, "QCatchSyscalls:"))
605 const char *p
= own_buf
+ sizeof ("QCatchSyscalls:") - 1;
608 struct process_info
*process
;
610 if (!target_running () || !target_supports_catch_syscall ())
616 if (strcmp (p
, "0") == 0)
618 else if (p
[0] == '1' && (p
[1] == ';' || p
[1] == '\0'))
622 fprintf (stderr
, "Unknown catch-syscalls mode requested: %s\n",
628 process
= current_process ();
629 process
->syscalls_to_catch
.clear ();
639 p
= decode_address_to_semicolon (&sysno
, p
);
640 process
->syscalls_to_catch
.push_back (sysno
);
644 process
->syscalls_to_catch
.push_back (ANY_SYSCALL
);
651 if (strcmp (own_buf
, "QEnvironmentReset") == 0)
653 our_environ
= gdb_environ::from_host_environ ();
659 if (startswith (own_buf
, "QEnvironmentHexEncoded:"))
661 const char *p
= own_buf
+ sizeof ("QEnvironmentHexEncoded:") - 1;
662 /* The final form of the environment variable. FINAL_VAR will
663 hold the 'VAR=VALUE' format. */
664 std::string final_var
= hex2str (p
);
665 std::string var_name
, var_value
;
669 debug_printf (_("[QEnvironmentHexEncoded received '%s']\n"), p
);
670 debug_printf (_("[Environment variable to be set: '%s']\n"),
675 size_t pos
= final_var
.find ('=');
676 if (pos
== std::string::npos
)
678 warning (_("Unexpected format for environment variable: '%s'"),
684 var_name
= final_var
.substr (0, pos
);
685 var_value
= final_var
.substr (pos
+ 1, std::string::npos
);
687 our_environ
.set (var_name
.c_str (), var_value
.c_str ());
693 if (startswith (own_buf
, "QEnvironmentUnset:"))
695 const char *p
= own_buf
+ sizeof ("QEnvironmentUnset:") - 1;
696 std::string varname
= hex2str (p
);
700 debug_printf (_("[QEnvironmentUnset received '%s']\n"), p
);
701 debug_printf (_("[Environment variable to be unset: '%s']\n"),
706 our_environ
.unset (varname
.c_str ());
712 if (strcmp (own_buf
, "QStartNoAckMode") == 0)
716 debug_printf ("[noack mode enabled]\n");
725 if (startswith (own_buf
, "QNonStop:"))
727 char *mode
= own_buf
+ 9;
731 if (strcmp (mode
, "0") == 0)
733 else if (strcmp (mode
, "1") == 0)
737 /* We don't know what this mode is, so complain to
739 fprintf (stderr
, "Unknown non-stop mode requested: %s\n",
745 req_str
= req
? "non-stop" : "all-stop";
746 if (start_non_stop (req
) != 0)
748 fprintf (stderr
, "Setting %s mode failed\n", req_str
);
756 debug_printf ("[%s mode enabled]\n", req_str
);
762 if (startswith (own_buf
, "QDisableRandomization:"))
764 char *packet
= own_buf
+ strlen ("QDisableRandomization:");
767 unpack_varlen_hex (packet
, &setting
);
768 cs
.disable_randomization
= setting
;
772 debug_printf (cs
.disable_randomization
773 ? "[address space randomization disabled]\n"
774 : "[address space randomization enabled]\n");
781 if (target_supports_tracepoints ()
782 && handle_tracepoint_general_set (own_buf
))
785 if (startswith (own_buf
, "QAgent:"))
787 char *mode
= own_buf
+ strlen ("QAgent:");
790 if (strcmp (mode
, "0") == 0)
792 else if (strcmp (mode
, "1") == 0)
796 /* We don't know what this value is, so complain to GDB. */
797 sprintf (own_buf
, "E.Unknown QAgent value");
801 /* Update the flag. */
804 debug_printf ("[%s agent]\n", req
? "Enable" : "Disable");
809 if (handle_btrace_general_set (own_buf
))
812 if (handle_btrace_conf_general_set (own_buf
))
815 if (startswith (own_buf
, "QThreadEvents:"))
817 char *mode
= own_buf
+ strlen ("QThreadEvents:");
818 enum tribool req
= TRIBOOL_UNKNOWN
;
820 if (strcmp (mode
, "0") == 0)
822 else if (strcmp (mode
, "1") == 0)
826 /* We don't know what this mode is, so complain to GDB. */
827 sprintf (own_buf
, "E.Unknown thread-events mode requested: %s\n",
832 cs
.report_thread_events
= (req
== TRIBOOL_TRUE
);
836 const char *req_str
= cs
.report_thread_events
? "enabled" : "disabled";
838 debug_printf ("[thread events are now %s]\n", req_str
);
845 if (startswith (own_buf
, "QStartupWithShell:"))
847 const char *value
= own_buf
+ strlen ("QStartupWithShell:");
849 if (strcmp (value
, "1") == 0)
850 startup_with_shell
= true;
851 else if (strcmp (value
, "0") == 0)
852 startup_with_shell
= false;
856 fprintf (stderr
, "Unknown value to startup-with-shell: %s\n",
863 debug_printf (_("[Inferior will %s started with shell]"),
864 startup_with_shell
? "be" : "not be");
870 if (startswith (own_buf
, "QSetWorkingDir:"))
872 const char *p
= own_buf
+ strlen ("QSetWorkingDir:");
876 std::string path
= hex2str (p
);
878 set_inferior_cwd (path
.c_str ());
881 debug_printf (_("[Set the inferior's current directory to %s]\n"),
886 /* An empty argument means that we should clear out any
887 previously set cwd for the inferior. */
888 set_inferior_cwd (NULL
);
892 [Unset the inferior's current directory; will use gdbserver's cwd]\n"));
899 /* Otherwise we didn't know what packet it was. Say we didn't
905 get_features_xml (const char *annex
)
907 const struct target_desc
*desc
= current_target_desc ();
909 /* `desc->xmltarget' defines what to return when looking for the
910 "target.xml" file. Its contents can either be verbatim XML code
911 (prefixed with a '@') or else the name of the actual XML file to
912 be used in place of "target.xml".
914 This variable is set up from the auto-generated
915 init_registers_... routine for the current target. */
917 if (strcmp (annex
, "target.xml") == 0)
919 const char *ret
= tdesc_get_features_xml (desc
);
929 extern const char *const xml_builtin
[][2];
932 /* Look for the annex. */
933 for (i
= 0; xml_builtin
[i
][0] != NULL
; i
++)
934 if (strcmp (annex
, xml_builtin
[i
][0]) == 0)
937 if (xml_builtin
[i
][0] != NULL
)
938 return xml_builtin
[i
][1];
946 monitor_show_help (void)
948 monitor_output ("The following monitor commands are supported:\n");
949 monitor_output (" set debug <0|1>\n");
950 monitor_output (" Enable general debugging messages\n");
951 monitor_output (" set debug-hw-points <0|1>\n");
952 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
953 monitor_output (" set remote-debug <0|1>\n");
954 monitor_output (" Enable remote protocol debugging messages\n");
955 monitor_output (" set debug-format option1[,option2,...]\n");
956 monitor_output (" Add additional information to debugging messages\n");
957 monitor_output (" Options: all, none");
958 monitor_output (", timestamp");
959 monitor_output ("\n");
960 monitor_output (" exit\n");
961 monitor_output (" Quit GDBserver\n");
964 /* Read trace frame or inferior memory. Returns the number of bytes
965 actually read, zero when no further transfer is possible, and -1 on
966 error. Return of a positive value smaller than LEN does not
967 indicate there's no more to be read, only the end of the transfer.
968 E.g., when GDB reads memory from a traceframe, a first request may
969 be served from a memory block that does not cover the whole request
970 length. A following request gets the rest served from either
971 another block (of the same traceframe) or from the read-only
975 gdb_read_memory (CORE_ADDR memaddr
, unsigned char *myaddr
, int len
)
977 client_state
&cs
= get_client_state ();
980 if (cs
.current_traceframe
>= 0)
983 ULONGEST length
= len
;
985 if (traceframe_read_mem (cs
.current_traceframe
,
986 memaddr
, myaddr
, len
, &nbytes
))
988 /* Data read from trace buffer, we're done. */
991 if (!in_readonly_region (memaddr
, length
))
993 /* Otherwise we have a valid readonly case, fall through. */
994 /* (assume no half-trace half-real blocks for now) */
997 res
= prepare_to_access_memory ();
1000 if (set_desired_thread ())
1001 res
= read_inferior_memory (memaddr
, myaddr
, len
);
1004 done_accessing_memory ();
1006 return res
== 0 ? len
: -1;
1012 /* Write trace frame or inferior memory. Actually, writing to trace
1013 frames is forbidden. */
1016 gdb_write_memory (CORE_ADDR memaddr
, const unsigned char *myaddr
, int len
)
1018 client_state
&cs
= get_client_state ();
1019 if (cs
.current_traceframe
>= 0)
1025 ret
= prepare_to_access_memory ();
1028 if (set_desired_thread ())
1029 ret
= target_write_memory (memaddr
, myaddr
, len
);
1032 done_accessing_memory ();
1038 /* Subroutine of handle_search_memory to simplify it. */
1041 handle_search_memory_1 (CORE_ADDR start_addr
, CORE_ADDR search_space_len
,
1042 gdb_byte
*pattern
, unsigned pattern_len
,
1043 gdb_byte
*search_buf
,
1044 unsigned chunk_size
, unsigned search_buf_size
,
1045 CORE_ADDR
*found_addrp
)
1047 /* Prime the search buffer. */
1049 if (gdb_read_memory (start_addr
, search_buf
, search_buf_size
)
1052 warning ("Unable to access %ld bytes of target "
1053 "memory at 0x%lx, halting search.",
1054 (long) search_buf_size
, (long) start_addr
);
1058 /* Perform the search.
1060 The loop is kept simple by allocating [N + pattern-length - 1] bytes.
1061 When we've scanned N bytes we copy the trailing bytes to the start and
1062 read in another N bytes. */
1064 while (search_space_len
>= pattern_len
)
1066 gdb_byte
*found_ptr
;
1067 unsigned nr_search_bytes
= (search_space_len
< search_buf_size
1071 found_ptr
= (gdb_byte
*) memmem (search_buf
, nr_search_bytes
, pattern
,
1074 if (found_ptr
!= NULL
)
1076 CORE_ADDR found_addr
= start_addr
+ (found_ptr
- search_buf
);
1077 *found_addrp
= found_addr
;
1081 /* Not found in this chunk, skip to next chunk. */
1083 /* Don't let search_space_len wrap here, it's unsigned. */
1084 if (search_space_len
>= chunk_size
)
1085 search_space_len
-= chunk_size
;
1087 search_space_len
= 0;
1089 if (search_space_len
>= pattern_len
)
1091 unsigned keep_len
= search_buf_size
- chunk_size
;
1092 CORE_ADDR read_addr
= start_addr
+ chunk_size
+ keep_len
;
1095 /* Copy the trailing part of the previous iteration to the front
1096 of the buffer for the next iteration. */
1097 memcpy (search_buf
, search_buf
+ chunk_size
, keep_len
);
1099 nr_to_read
= (search_space_len
- keep_len
< chunk_size
1100 ? search_space_len
- keep_len
1103 if (gdb_read_memory (read_addr
, search_buf
+ keep_len
,
1104 nr_to_read
) != search_buf_size
)
1106 warning ("Unable to access %ld bytes of target memory "
1107 "at 0x%lx, halting search.",
1108 (long) nr_to_read
, (long) read_addr
);
1112 start_addr
+= chunk_size
;
1121 /* Handle qSearch:memory packets. */
1124 handle_search_memory (char *own_buf
, int packet_len
)
1126 CORE_ADDR start_addr
;
1127 CORE_ADDR search_space_len
;
1129 unsigned int pattern_len
;
1130 /* NOTE: also defined in find.c testcase. */
1131 #define SEARCH_CHUNK_SIZE 16000
1132 const unsigned chunk_size
= SEARCH_CHUNK_SIZE
;
1133 /* Buffer to hold memory contents for searching. */
1134 gdb_byte
*search_buf
;
1135 unsigned search_buf_size
;
1137 CORE_ADDR found_addr
;
1138 int cmd_name_len
= sizeof ("qSearch:memory:") - 1;
1140 pattern
= (gdb_byte
*) malloc (packet_len
);
1141 if (pattern
== NULL
)
1143 error ("Unable to allocate memory to perform the search");
1144 strcpy (own_buf
, "E00");
1147 if (decode_search_memory_packet (own_buf
+ cmd_name_len
,
1148 packet_len
- cmd_name_len
,
1149 &start_addr
, &search_space_len
,
1150 pattern
, &pattern_len
) < 0)
1153 error ("Error in parsing qSearch:memory packet");
1154 strcpy (own_buf
, "E00");
1158 search_buf_size
= chunk_size
+ pattern_len
- 1;
1160 /* No point in trying to allocate a buffer larger than the search space. */
1161 if (search_space_len
< search_buf_size
)
1162 search_buf_size
= search_space_len
;
1164 search_buf
= (gdb_byte
*) malloc (search_buf_size
);
1165 if (search_buf
== NULL
)
1168 error ("Unable to allocate memory to perform the search");
1169 strcpy (own_buf
, "E00");
1173 found
= handle_search_memory_1 (start_addr
, search_space_len
,
1174 pattern
, pattern_len
,
1175 search_buf
, chunk_size
, search_buf_size
,
1179 sprintf (own_buf
, "1,%lx", (long) found_addr
);
1180 else if (found
== 0)
1181 strcpy (own_buf
, "0");
1183 strcpy (own_buf
, "E00");
1189 /* Handle the "D" packet. */
1192 handle_detach (char *own_buf
)
1194 client_state
&cs
= get_client_state ();
1196 process_info
*process
;
1198 if (cs
.multi_process
)
1201 int pid
= strtol (&own_buf
[2], NULL
, 16);
1203 process
= find_process_pid (pid
);
1207 process
= (current_thread
!= nullptr
1208 ? get_thread_process (current_thread
)
1212 if (process
== NULL
)
1214 write_enn (own_buf
);
1218 if ((tracing
&& disconnected_tracing
) || any_persistent_commands (process
))
1220 if (tracing
&& disconnected_tracing
)
1222 "Disconnected tracing in effect, "
1223 "leaving gdbserver attached to the process\n");
1225 if (any_persistent_commands (process
))
1227 "Persistent commands are present, "
1228 "leaving gdbserver attached to the process\n");
1230 /* Make sure we're in non-stop/async mode, so we we can both
1231 wait for an async socket accept, and handle async target
1232 events simultaneously. There's also no point either in
1233 having the target stop all threads, when we're going to
1234 pass signals down without informing GDB. */
1238 debug_printf ("Forcing non-stop mode\n");
1244 process
->gdb_detached
= 1;
1246 /* Detaching implicitly resumes all threads. */
1247 target_continue_no_signal (minus_one_ptid
);
1253 fprintf (stderr
, "Detaching from process %d\n", process
->pid
);
1256 /* We'll need this after PROCESS has been destroyed. */
1257 int pid
= process
->pid
;
1259 if (detach_inferior (process
) != 0)
1260 write_enn (own_buf
);
1263 discard_queued_stop_replies (ptid_t (pid
));
1266 if (extended_protocol
|| target_running ())
1268 /* There is still at least one inferior remaining or
1269 we are in extended mode, so don't terminate gdbserver,
1270 and instead treat this like a normal program exit. */
1271 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
1272 cs
.last_status
.value
.integer
= 0;
1273 cs
.last_ptid
= ptid_t (pid
);
1275 current_thread
= NULL
;
1282 /* If we are attached, then we can exit. Otherwise, we
1283 need to hang around doing nothing, until the child is
1285 join_inferior (pid
);
1291 /* Parse options to --debug-format= and "monitor set debug-format".
1292 ARG is the text after "--debug-format=" or "monitor set debug-format".
1293 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1294 This triggers calls to monitor_output.
1295 The result is an empty string if all options were parsed ok, otherwise an
1296 error message which the caller must free.
1298 N.B. These commands affect all debug format settings, they are not
1299 cumulative. If a format is not specified, it is turned off.
1300 However, we don't go to extra trouble with things like
1301 "monitor set debug-format all,none,timestamp".
1302 Instead we just parse them one at a time, in order.
1304 The syntax for "monitor set debug" we support here is not identical
1305 to gdb's "set debug foo on|off" because we also use this function to
1306 parse "--debug-format=foo,bar". */
1309 parse_debug_format_options (const char *arg
, int is_monitor
)
1311 /* First turn all debug format options off. */
1312 debug_timestamp
= 0;
1314 /* First remove leading spaces, for "monitor set debug-format". */
1315 while (isspace (*arg
))
1318 std::vector
<gdb::unique_xmalloc_ptr
<char>> options
1319 = delim_string_to_char_ptr_vec (arg
, ',');
1321 for (const gdb::unique_xmalloc_ptr
<char> &option
: options
)
1323 if (strcmp (option
.get (), "all") == 0)
1325 debug_timestamp
= 1;
1327 monitor_output ("All extra debug format options enabled.\n");
1329 else if (strcmp (option
.get (), "none") == 0)
1331 debug_timestamp
= 0;
1333 monitor_output ("All extra debug format options disabled.\n");
1335 else if (strcmp (option
.get (), "timestamp") == 0)
1337 debug_timestamp
= 1;
1339 monitor_output ("Timestamps will be added to debug output.\n");
1341 else if (*option
== '\0')
1343 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1347 return string_printf ("Unknown debug-format argument: \"%s\"\n",
1351 return std::string ();
1354 /* Handle monitor commands not handled by target-specific handlers. */
1357 handle_monitor_command (char *mon
, char *own_buf
)
1359 if (strcmp (mon
, "set debug 1") == 0)
1362 monitor_output ("Debug output enabled.\n");
1364 else if (strcmp (mon
, "set debug 0") == 0)
1367 monitor_output ("Debug output disabled.\n");
1369 else if (strcmp (mon
, "set debug-hw-points 1") == 0)
1371 show_debug_regs
= 1;
1372 monitor_output ("H/W point debugging output enabled.\n");
1374 else if (strcmp (mon
, "set debug-hw-points 0") == 0)
1376 show_debug_regs
= 0;
1377 monitor_output ("H/W point debugging output disabled.\n");
1379 else if (strcmp (mon
, "set remote-debug 1") == 0)
1382 monitor_output ("Protocol debug output enabled.\n");
1384 else if (strcmp (mon
, "set remote-debug 0") == 0)
1387 monitor_output ("Protocol debug output disabled.\n");
1389 else if (startswith (mon
, "set debug-format "))
1391 std::string error_msg
1392 = parse_debug_format_options (mon
+ sizeof ("set debug-format ") - 1,
1395 if (!error_msg
.empty ())
1397 monitor_output (error_msg
.c_str ());
1398 monitor_show_help ();
1399 write_enn (own_buf
);
1402 else if (strcmp (mon
, "set debug-file") == 0)
1403 debug_set_output (nullptr);
1404 else if (startswith (mon
, "set debug-file "))
1405 debug_set_output (mon
+ sizeof ("set debug-file ") - 1);
1406 else if (strcmp (mon
, "help") == 0)
1407 monitor_show_help ();
1408 else if (strcmp (mon
, "exit") == 0)
1412 monitor_output ("Unknown monitor command.\n\n");
1413 monitor_show_help ();
1414 write_enn (own_buf
);
1418 /* Associates a callback with each supported qXfer'able object. */
1422 /* The object this handler handles. */
1425 /* Request that the target transfer up to LEN 8-bit bytes of the
1426 target's OBJECT. The OFFSET, for a seekable object, specifies
1427 the starting point. The ANNEX can be used to provide additional
1428 data-specific information to the target.
1430 Return the number of bytes actually transfered, zero when no
1431 further transfer is possible, -1 on error, -2 when the transfer
1432 is not supported, and -3 on a verbose error message that should
1433 be preserved. Return of a positive value smaller than LEN does
1434 not indicate the end of the object, only the end of the transfer.
1436 One, and only one, of readbuf or writebuf must be non-NULL. */
1437 int (*xfer
) (const char *annex
,
1438 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1439 ULONGEST offset
, LONGEST len
);
1442 /* Handle qXfer:auxv:read. */
1445 handle_qxfer_auxv (const char *annex
,
1446 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1447 ULONGEST offset
, LONGEST len
)
1449 if (the_target
->read_auxv
== NULL
|| writebuf
!= NULL
)
1452 if (annex
[0] != '\0' || current_thread
== NULL
)
1455 return (*the_target
->read_auxv
) (offset
, readbuf
, len
);
1458 /* Handle qXfer:exec-file:read. */
1461 handle_qxfer_exec_file (const char *annex
,
1462 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1463 ULONGEST offset
, LONGEST len
)
1469 if (the_target
->pid_to_exec_file
== NULL
|| writebuf
!= NULL
)
1472 if (annex
[0] == '\0')
1474 if (current_thread
== NULL
)
1477 pid
= pid_of (current_thread
);
1481 annex
= unpack_varlen_hex (annex
, &pid
);
1482 if (annex
[0] != '\0')
1489 file
= (*the_target
->pid_to_exec_file
) (pid
);
1493 total_len
= strlen (file
);
1495 if (offset
> total_len
)
1498 if (offset
+ len
> total_len
)
1499 len
= total_len
- offset
;
1501 memcpy (readbuf
, file
+ offset
, len
);
1505 /* Handle qXfer:features:read. */
1508 handle_qxfer_features (const char *annex
,
1509 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1510 ULONGEST offset
, LONGEST len
)
1512 const char *document
;
1515 if (writebuf
!= NULL
)
1518 if (!target_running ())
1521 /* Grab the correct annex. */
1522 document
= get_features_xml (annex
);
1523 if (document
== NULL
)
1526 total_len
= strlen (document
);
1528 if (offset
> total_len
)
1531 if (offset
+ len
> total_len
)
1532 len
= total_len
- offset
;
1534 memcpy (readbuf
, document
+ offset
, len
);
1538 /* Handle qXfer:libraries:read. */
1541 handle_qxfer_libraries (const char *annex
,
1542 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1543 ULONGEST offset
, LONGEST len
)
1545 if (writebuf
!= NULL
)
1548 if (annex
[0] != '\0' || current_thread
== NULL
)
1551 std::string document
= "<library-list version=\"1.0\">\n";
1553 for (const dll_info
&dll
: all_dlls
)
1554 document
+= string_printf
1555 (" <library name=\"%s\"><segment address=\"0x%lx\"/></library>\n",
1556 dll
.name
.c_str (), (long) dll
.base_addr
);
1558 document
+= "</library-list>\n";
1560 if (offset
> document
.length ())
1563 if (offset
+ len
> document
.length ())
1564 len
= document
.length () - offset
;
1566 memcpy (readbuf
, &document
[offset
], len
);
1571 /* Handle qXfer:libraries-svr4:read. */
1574 handle_qxfer_libraries_svr4 (const char *annex
,
1575 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1576 ULONGEST offset
, LONGEST len
)
1578 if (writebuf
!= NULL
)
1581 if (current_thread
== NULL
|| the_target
->qxfer_libraries_svr4
== NULL
)
1584 return the_target
->qxfer_libraries_svr4 (annex
, readbuf
, writebuf
, offset
, len
);
1587 /* Handle qXfer:osadata:read. */
1590 handle_qxfer_osdata (const char *annex
,
1591 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1592 ULONGEST offset
, LONGEST len
)
1594 if (the_target
->qxfer_osdata
== NULL
|| writebuf
!= NULL
)
1597 return (*the_target
->qxfer_osdata
) (annex
, readbuf
, NULL
, offset
, len
);
1600 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1603 handle_qxfer_siginfo (const char *annex
,
1604 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1605 ULONGEST offset
, LONGEST len
)
1607 if (the_target
->qxfer_siginfo
== NULL
)
1610 if (annex
[0] != '\0' || current_thread
== NULL
)
1613 return (*the_target
->qxfer_siginfo
) (annex
, readbuf
, writebuf
, offset
, len
);
1616 /* Handle qXfer:statictrace:read. */
1619 handle_qxfer_statictrace (const char *annex
,
1620 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1621 ULONGEST offset
, LONGEST len
)
1623 client_state
&cs
= get_client_state ();
1626 if (writebuf
!= NULL
)
1629 if (annex
[0] != '\0' || current_thread
== NULL
1630 || cs
.current_traceframe
== -1)
1633 if (traceframe_read_sdata (cs
.current_traceframe
, offset
,
1634 readbuf
, len
, &nbytes
))
1639 /* Helper for handle_qxfer_threads_proper.
1640 Emit the XML to describe the thread of INF. */
1643 handle_qxfer_threads_worker (thread_info
*thread
, struct buffer
*buffer
)
1645 ptid_t ptid
= ptid_of (thread
);
1647 int core
= target_core_of_thread (ptid
);
1649 const char *name
= target_thread_name (ptid
);
1652 bool handle_status
= target_thread_handle (ptid
, &handle
, &handle_len
);
1654 write_ptid (ptid_s
, ptid
);
1656 buffer_xml_printf (buffer
, "<thread id=\"%s\"", ptid_s
);
1660 sprintf (core_s
, "%d", core
);
1661 buffer_xml_printf (buffer
, " core=\"%s\"", core_s
);
1665 buffer_xml_printf (buffer
, " name=\"%s\"", name
);
1669 char *handle_s
= (char *) alloca (handle_len
* 2 + 1);
1670 bin2hex (handle
, handle_s
, handle_len
);
1671 buffer_xml_printf (buffer
, " handle=\"%s\"", handle_s
);
1674 buffer_xml_printf (buffer
, "/>\n");
1677 /* Helper for handle_qxfer_threads. */
1680 handle_qxfer_threads_proper (struct buffer
*buffer
)
1682 buffer_grow_str (buffer
, "<threads>\n");
1684 for_each_thread ([&] (thread_info
*thread
)
1686 handle_qxfer_threads_worker (thread
, buffer
);
1689 buffer_grow_str0 (buffer
, "</threads>\n");
1692 /* Handle qXfer:threads:read. */
1695 handle_qxfer_threads (const char *annex
,
1696 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1697 ULONGEST offset
, LONGEST len
)
1699 static char *result
= 0;
1700 static unsigned int result_length
= 0;
1702 if (writebuf
!= NULL
)
1705 if (annex
[0] != '\0')
1710 struct buffer buffer
;
1711 /* When asked for data at offset 0, generate everything and store into
1712 'result'. Successive reads will be served off 'result'. */
1716 buffer_init (&buffer
);
1718 handle_qxfer_threads_proper (&buffer
);
1720 result
= buffer_finish (&buffer
);
1721 result_length
= strlen (result
);
1722 buffer_free (&buffer
);
1725 if (offset
>= result_length
)
1727 /* We're out of data. */
1734 if (len
> result_length
- offset
)
1735 len
= result_length
- offset
;
1737 memcpy (readbuf
, result
+ offset
, len
);
1742 /* Handle qXfer:traceframe-info:read. */
1745 handle_qxfer_traceframe_info (const char *annex
,
1746 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1747 ULONGEST offset
, LONGEST len
)
1749 client_state
&cs
= get_client_state ();
1750 static char *result
= 0;
1751 static unsigned int result_length
= 0;
1753 if (writebuf
!= NULL
)
1756 if (!target_running () || annex
[0] != '\0' || cs
.current_traceframe
== -1)
1761 struct buffer buffer
;
1763 /* When asked for data at offset 0, generate everything and
1764 store into 'result'. Successive reads will be served off
1768 buffer_init (&buffer
);
1770 traceframe_read_info (cs
.current_traceframe
, &buffer
);
1772 result
= buffer_finish (&buffer
);
1773 result_length
= strlen (result
);
1774 buffer_free (&buffer
);
1777 if (offset
>= result_length
)
1779 /* We're out of data. */
1786 if (len
> result_length
- offset
)
1787 len
= result_length
- offset
;
1789 memcpy (readbuf
, result
+ offset
, len
);
1793 /* Handle qXfer:fdpic:read. */
1796 handle_qxfer_fdpic (const char *annex
, gdb_byte
*readbuf
,
1797 const gdb_byte
*writebuf
, ULONGEST offset
, LONGEST len
)
1799 if (the_target
->read_loadmap
== NULL
)
1802 if (current_thread
== NULL
)
1805 return (*the_target
->read_loadmap
) (annex
, offset
, readbuf
, len
);
1808 /* Handle qXfer:btrace:read. */
1811 handle_qxfer_btrace (const char *annex
,
1812 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1813 ULONGEST offset
, LONGEST len
)
1815 client_state
&cs
= get_client_state ();
1816 static struct buffer cache
;
1817 struct thread_info
*thread
;
1818 enum btrace_read_type type
;
1821 if (writebuf
!= NULL
)
1824 if (cs
.general_thread
== null_ptid
1825 || cs
.general_thread
== minus_one_ptid
)
1827 strcpy (cs
.own_buf
, "E.Must select a single thread.");
1831 thread
= find_thread_ptid (cs
.general_thread
);
1834 strcpy (cs
.own_buf
, "E.No such thread.");
1838 if (thread
->btrace
== NULL
)
1840 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
1844 if (strcmp (annex
, "all") == 0)
1845 type
= BTRACE_READ_ALL
;
1846 else if (strcmp (annex
, "new") == 0)
1847 type
= BTRACE_READ_NEW
;
1848 else if (strcmp (annex
, "delta") == 0)
1849 type
= BTRACE_READ_DELTA
;
1852 strcpy (cs
.own_buf
, "E.Bad annex.");
1858 buffer_free (&cache
);
1862 result
= target_read_btrace (thread
->btrace
, &cache
, type
);
1864 memcpy (cs
.own_buf
, cache
.buffer
, cache
.used_size
);
1866 catch (const gdb_exception_error
&exception
)
1868 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
1875 else if (offset
> cache
.used_size
)
1877 buffer_free (&cache
);
1881 if (len
> cache
.used_size
- offset
)
1882 len
= cache
.used_size
- offset
;
1884 memcpy (readbuf
, cache
.buffer
+ offset
, len
);
1889 /* Handle qXfer:btrace-conf:read. */
1892 handle_qxfer_btrace_conf (const char *annex
,
1893 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1894 ULONGEST offset
, LONGEST len
)
1896 client_state
&cs
= get_client_state ();
1897 static struct buffer cache
;
1898 struct thread_info
*thread
;
1901 if (writebuf
!= NULL
)
1904 if (annex
[0] != '\0')
1907 if (cs
.general_thread
== null_ptid
1908 || cs
.general_thread
== minus_one_ptid
)
1910 strcpy (cs
.own_buf
, "E.Must select a single thread.");
1914 thread
= find_thread_ptid (cs
.general_thread
);
1917 strcpy (cs
.own_buf
, "E.No such thread.");
1921 if (thread
->btrace
== NULL
)
1923 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
1929 buffer_free (&cache
);
1933 result
= target_read_btrace_conf (thread
->btrace
, &cache
);
1935 memcpy (cs
.own_buf
, cache
.buffer
, cache
.used_size
);
1937 catch (const gdb_exception_error
&exception
)
1939 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
1946 else if (offset
> cache
.used_size
)
1948 buffer_free (&cache
);
1952 if (len
> cache
.used_size
- offset
)
1953 len
= cache
.used_size
- offset
;
1955 memcpy (readbuf
, cache
.buffer
+ offset
, len
);
1960 static const struct qxfer qxfer_packets
[] =
1962 { "auxv", handle_qxfer_auxv
},
1963 { "btrace", handle_qxfer_btrace
},
1964 { "btrace-conf", handle_qxfer_btrace_conf
},
1965 { "exec-file", handle_qxfer_exec_file
},
1966 { "fdpic", handle_qxfer_fdpic
},
1967 { "features", handle_qxfer_features
},
1968 { "libraries", handle_qxfer_libraries
},
1969 { "libraries-svr4", handle_qxfer_libraries_svr4
},
1970 { "osdata", handle_qxfer_osdata
},
1971 { "siginfo", handle_qxfer_siginfo
},
1972 { "statictrace", handle_qxfer_statictrace
},
1973 { "threads", handle_qxfer_threads
},
1974 { "traceframe-info", handle_qxfer_traceframe_info
},
1978 handle_qxfer (char *own_buf
, int packet_len
, int *new_packet_len_p
)
1986 if (!startswith (own_buf
, "qXfer:"))
1989 /* Grab the object, r/w and annex. */
1990 if (decode_xfer (own_buf
+ 6, &object
, &rw
, &annex
, &offset
) < 0)
1992 write_enn (own_buf
);
1997 i
< sizeof (qxfer_packets
) / sizeof (qxfer_packets
[0]);
2000 const struct qxfer
*q
= &qxfer_packets
[i
];
2002 if (strcmp (object
, q
->object
) == 0)
2004 if (strcmp (rw
, "read") == 0)
2006 unsigned char *data
;
2011 /* Grab the offset and length. */
2012 if (decode_xfer_read (offset
, &ofs
, &len
) < 0)
2014 write_enn (own_buf
);
2018 /* Read one extra byte, as an indicator of whether there is
2020 if (len
> PBUFSIZ
- 2)
2022 data
= (unsigned char *) malloc (len
+ 1);
2025 write_enn (own_buf
);
2028 n
= (*q
->xfer
) (annex
, data
, NULL
, ofs
, len
+ 1);
2036 /* Preserve error message. */
2039 write_enn (own_buf
);
2041 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, len
, 1);
2043 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, n
, 0);
2048 else if (strcmp (rw
, "write") == 0)
2053 unsigned char *data
;
2055 strcpy (own_buf
, "E00");
2056 data
= (unsigned char *) malloc (packet_len
- (offset
- own_buf
));
2059 write_enn (own_buf
);
2062 if (decode_xfer_write (offset
, packet_len
- (offset
- own_buf
),
2063 &ofs
, &len
, data
) < 0)
2066 write_enn (own_buf
);
2070 n
= (*q
->xfer
) (annex
, NULL
, data
, ofs
, len
);
2078 /* Preserve error message. */
2081 write_enn (own_buf
);
2083 sprintf (own_buf
, "%x", n
);
2096 /* Compute 32 bit CRC from inferior memory.
2098 On success, return 32 bit CRC.
2099 On failure, return (unsigned long long) -1. */
2101 static unsigned long long
2102 crc32 (CORE_ADDR base
, int len
, unsigned int crc
)
2106 unsigned char byte
= 0;
2108 /* Return failure if memory read fails. */
2109 if (read_inferior_memory (base
, &byte
, 1) != 0)
2110 return (unsigned long long) -1;
2112 crc
= xcrc32 (&byte
, 1, crc
);
2115 return (unsigned long long) crc
;
2118 /* Add supported btrace packets to BUF. */
2121 supported_btrace_packets (char *buf
)
2123 strcat (buf
, ";Qbtrace:bts+");
2124 strcat (buf
, ";Qbtrace-conf:bts:size+");
2125 strcat (buf
, ";Qbtrace:pt+");
2126 strcat (buf
, ";Qbtrace-conf:pt:size+");
2127 strcat (buf
, ";Qbtrace:off+");
2128 strcat (buf
, ";qXfer:btrace:read+");
2129 strcat (buf
, ";qXfer:btrace-conf:read+");
2132 /* Handle all of the extended 'q' packets. */
2135 handle_query (char *own_buf
, int packet_len
, int *new_packet_len_p
)
2137 client_state
&cs
= get_client_state ();
2138 static std::list
<thread_info
*>::const_iterator thread_iter
;
2140 /* Reply the current thread id. */
2141 if (strcmp ("qC", own_buf
) == 0 && !disable_packet_qC
)
2144 require_running_or_return (own_buf
);
2146 if (cs
.general_thread
!= null_ptid
&& cs
.general_thread
!= minus_one_ptid
)
2147 ptid
= cs
.general_thread
;
2150 thread_iter
= all_threads
.begin ();
2151 ptid
= (*thread_iter
)->id
;
2154 sprintf (own_buf
, "QC");
2156 write_ptid (own_buf
, ptid
);
2160 if (strcmp ("qSymbol::", own_buf
) == 0)
2162 struct thread_info
*save_thread
= current_thread
;
2164 /* For qSymbol, GDB only changes the current thread if the
2165 previous current thread was of a different process. So if
2166 the previous thread is gone, we need to pick another one of
2167 the same process. This can happen e.g., if we followed an
2168 exec in a non-leader thread. */
2169 if (current_thread
== NULL
)
2172 = find_any_thread_of_pid (cs
.general_thread
.pid ());
2174 /* Just in case, if we didn't find a thread, then bail out
2175 instead of crashing. */
2176 if (current_thread
== NULL
)
2178 write_enn (own_buf
);
2179 current_thread
= save_thread
;
2184 /* GDB is suggesting new symbols have been loaded. This may
2185 mean a new shared library has been detected as loaded, so
2186 take the opportunity to check if breakpoints we think are
2187 inserted, still are. Note that it isn't guaranteed that
2188 we'll see this when a shared library is loaded, and nor will
2189 we see this for unloads (although breakpoints in unloaded
2190 libraries shouldn't trigger), as GDB may not find symbols for
2191 the library at all. We also re-validate breakpoints when we
2192 see a second GDB breakpoint for the same address, and or when
2193 we access breakpoint shadows. */
2194 validate_breakpoints ();
2196 if (target_supports_tracepoints ())
2197 tracepoint_look_up_symbols ();
2199 if (current_thread
!= NULL
&& the_target
->look_up_symbols
!= NULL
)
2200 (*the_target
->look_up_symbols
) ();
2202 current_thread
= save_thread
;
2204 strcpy (own_buf
, "OK");
2208 if (!disable_packet_qfThreadInfo
)
2210 if (strcmp ("qfThreadInfo", own_buf
) == 0)
2212 require_running_or_return (own_buf
);
2213 thread_iter
= all_threads
.begin ();
2216 ptid_t ptid
= (*thread_iter
)->id
;
2217 write_ptid (own_buf
, ptid
);
2222 if (strcmp ("qsThreadInfo", own_buf
) == 0)
2224 require_running_or_return (own_buf
);
2225 if (thread_iter
!= all_threads
.end ())
2228 ptid_t ptid
= (*thread_iter
)->id
;
2229 write_ptid (own_buf
, ptid
);
2235 sprintf (own_buf
, "l");
2241 if (the_target
->read_offsets
!= NULL
2242 && strcmp ("qOffsets", own_buf
) == 0)
2244 CORE_ADDR text
, data
;
2246 require_running_or_return (own_buf
);
2247 if (the_target
->read_offsets (&text
, &data
))
2248 sprintf (own_buf
, "Text=%lX;Data=%lX;Bss=%lX",
2249 (long)text
, (long)data
, (long)data
);
2251 write_enn (own_buf
);
2256 /* Protocol features query. */
2257 if (startswith (own_buf
, "qSupported")
2258 && (own_buf
[10] == ':' || own_buf
[10] == '\0'))
2260 char *p
= &own_buf
[10];
2261 int gdb_supports_qRelocInsn
= 0;
2263 /* Process each feature being provided by GDB. The first
2264 feature will follow a ':', and latter features will follow
2268 char **qsupported
= NULL
;
2273 /* Two passes, to avoid nested strtok calls in
2274 target_process_qsupported. */
2275 for (p
= strtok (p
+ 1, ";");
2277 p
= strtok (NULL
, ";"))
2280 qsupported
= XRESIZEVEC (char *, qsupported
, count
);
2281 qsupported
[count
- 1] = xstrdup (p
);
2284 for (i
= 0; i
< count
; i
++)
2287 if (strcmp (p
, "multiprocess+") == 0)
2289 /* GDB supports and wants multi-process support if
2291 if (target_supports_multi_process ())
2292 cs
.multi_process
= 1;
2294 else if (strcmp (p
, "qRelocInsn+") == 0)
2296 /* GDB supports relocate instruction requests. */
2297 gdb_supports_qRelocInsn
= 1;
2299 else if (strcmp (p
, "swbreak+") == 0)
2301 /* GDB wants us to report whether a trap is caused
2302 by a software breakpoint and for us to handle PC
2303 adjustment if necessary on this target. */
2304 if (target_supports_stopped_by_sw_breakpoint ())
2305 cs
.swbreak_feature
= 1;
2307 else if (strcmp (p
, "hwbreak+") == 0)
2309 /* GDB wants us to report whether a trap is caused
2310 by a hardware breakpoint. */
2311 if (target_supports_stopped_by_hw_breakpoint ())
2312 cs
.hwbreak_feature
= 1;
2314 else if (strcmp (p
, "fork-events+") == 0)
2316 /* GDB supports and wants fork events if possible. */
2317 if (target_supports_fork_events ())
2318 cs
.report_fork_events
= 1;
2320 else if (strcmp (p
, "vfork-events+") == 0)
2322 /* GDB supports and wants vfork events if possible. */
2323 if (target_supports_vfork_events ())
2324 cs
.report_vfork_events
= 1;
2326 else if (strcmp (p
, "exec-events+") == 0)
2328 /* GDB supports and wants exec events if possible. */
2329 if (target_supports_exec_events ())
2330 cs
.report_exec_events
= 1;
2332 else if (strcmp (p
, "vContSupported+") == 0)
2333 cs
.vCont_supported
= 1;
2334 else if (strcmp (p
, "QThreadEvents+") == 0)
2336 else if (strcmp (p
, "no-resumed+") == 0)
2338 /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
2340 report_no_resumed
= 1;
2344 /* Move the unknown features all together. */
2345 qsupported
[i
] = NULL
;
2346 qsupported
[unknown
] = p
;
2351 /* Give the target backend a chance to process the unknown
2353 target_process_qsupported (qsupported
, unknown
);
2355 for (i
= 0; i
< count
; i
++)
2356 free (qsupported
[i
]);
2361 "PacketSize=%x;QPassSignals+;QProgramSignals+;"
2362 "QStartupWithShell+;QEnvironmentHexEncoded+;"
2363 "QEnvironmentReset+;QEnvironmentUnset+;"
2367 if (target_supports_catch_syscall ())
2368 strcat (own_buf
, ";QCatchSyscalls+");
2370 if (the_target
->qxfer_libraries_svr4
!= NULL
)
2371 strcat (own_buf
, ";qXfer:libraries-svr4:read+"
2372 ";augmented-libraries-svr4-read+");
2375 /* We do not have any hook to indicate whether the non-SVR4 target
2376 backend supports qXfer:libraries:read, so always report it. */
2377 strcat (own_buf
, ";qXfer:libraries:read+");
2380 if (the_target
->read_auxv
!= NULL
)
2381 strcat (own_buf
, ";qXfer:auxv:read+");
2383 if (the_target
->qxfer_siginfo
!= NULL
)
2384 strcat (own_buf
, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2386 if (the_target
->read_loadmap
!= NULL
)
2387 strcat (own_buf
, ";qXfer:fdpic:read+");
2389 /* We always report qXfer:features:read, as targets may
2390 install XML files on a subsequent call to arch_setup.
2391 If we reported to GDB on startup that we don't support
2392 qXfer:feature:read at all, we will never be re-queried. */
2393 strcat (own_buf
, ";qXfer:features:read+");
2395 if (cs
.transport_is_reliable
)
2396 strcat (own_buf
, ";QStartNoAckMode+");
2398 if (the_target
->qxfer_osdata
!= NULL
)
2399 strcat (own_buf
, ";qXfer:osdata:read+");
2401 if (target_supports_multi_process ())
2402 strcat (own_buf
, ";multiprocess+");
2404 if (target_supports_fork_events ())
2405 strcat (own_buf
, ";fork-events+");
2407 if (target_supports_vfork_events ())
2408 strcat (own_buf
, ";vfork-events+");
2410 if (target_supports_exec_events ())
2411 strcat (own_buf
, ";exec-events+");
2413 if (target_supports_non_stop ())
2414 strcat (own_buf
, ";QNonStop+");
2416 if (target_supports_disable_randomization ())
2417 strcat (own_buf
, ";QDisableRandomization+");
2419 strcat (own_buf
, ";qXfer:threads:read+");
2421 if (target_supports_tracepoints ())
2423 strcat (own_buf
, ";ConditionalTracepoints+");
2424 strcat (own_buf
, ";TraceStateVariables+");
2425 strcat (own_buf
, ";TracepointSource+");
2426 strcat (own_buf
, ";DisconnectedTracing+");
2427 if (gdb_supports_qRelocInsn
&& target_supports_fast_tracepoints ())
2428 strcat (own_buf
, ";FastTracepoints+");
2429 strcat (own_buf
, ";StaticTracepoints+");
2430 strcat (own_buf
, ";InstallInTrace+");
2431 strcat (own_buf
, ";qXfer:statictrace:read+");
2432 strcat (own_buf
, ";qXfer:traceframe-info:read+");
2433 strcat (own_buf
, ";EnableDisableTracepoints+");
2434 strcat (own_buf
, ";QTBuffer:size+");
2435 strcat (own_buf
, ";tracenz+");
2438 if (target_supports_hardware_single_step ()
2439 || target_supports_software_single_step () )
2441 strcat (own_buf
, ";ConditionalBreakpoints+");
2443 strcat (own_buf
, ";BreakpointCommands+");
2445 if (target_supports_agent ())
2446 strcat (own_buf
, ";QAgent+");
2448 supported_btrace_packets (own_buf
);
2450 if (target_supports_stopped_by_sw_breakpoint ())
2451 strcat (own_buf
, ";swbreak+");
2453 if (target_supports_stopped_by_hw_breakpoint ())
2454 strcat (own_buf
, ";hwbreak+");
2456 if (the_target
->pid_to_exec_file
!= NULL
)
2457 strcat (own_buf
, ";qXfer:exec-file:read+");
2459 strcat (own_buf
, ";vContSupported+");
2461 strcat (own_buf
, ";QThreadEvents+");
2463 strcat (own_buf
, ";no-resumed+");
2465 /* Reinitialize components as needed for the new connection. */
2466 hostio_handle_new_gdb_connection ();
2467 target_handle_new_gdb_connection ();
2472 /* Thread-local storage support. */
2473 if (the_target
->get_tls_address
!= NULL
2474 && startswith (own_buf
, "qGetTLSAddr:"))
2476 char *p
= own_buf
+ 12;
2477 CORE_ADDR parts
[2], address
= 0;
2479 ptid_t ptid
= null_ptid
;
2481 require_running_or_return (own_buf
);
2483 for (i
= 0; i
< 3; i
++)
2491 p2
= strchr (p
, ',');
2504 ptid
= read_ptid (p
, NULL
);
2506 decode_address (&parts
[i
- 1], p
, len
);
2510 if (p
!= NULL
|| i
< 3)
2514 struct thread_info
*thread
= find_thread_ptid (ptid
);
2519 err
= the_target
->get_tls_address (thread
, parts
[0], parts
[1],
2525 strcpy (own_buf
, paddress(address
));
2530 write_enn (own_buf
);
2534 /* Otherwise, pretend we do not understand this packet. */
2537 /* Windows OS Thread Information Block address support. */
2538 if (the_target
->get_tib_address
!= NULL
2539 && startswith (own_buf
, "qGetTIBAddr:"))
2544 ptid_t ptid
= read_ptid (own_buf
+ 12, &annex
);
2546 n
= (*the_target
->get_tib_address
) (ptid
, &tlb
);
2549 strcpy (own_buf
, paddress(tlb
));
2554 write_enn (own_buf
);
2560 /* Handle "monitor" commands. */
2561 if (startswith (own_buf
, "qRcmd,"))
2563 char *mon
= (char *) malloc (PBUFSIZ
);
2564 int len
= strlen (own_buf
+ 6);
2568 write_enn (own_buf
);
2573 || hex2bin (own_buf
+ 6, (gdb_byte
*) mon
, len
/ 2) != len
/ 2)
2575 write_enn (own_buf
);
2579 mon
[len
/ 2] = '\0';
2583 if (the_target
->handle_monitor_command
== NULL
2584 || (*the_target
->handle_monitor_command
) (mon
) == 0)
2585 /* Default processing. */
2586 handle_monitor_command (mon
, own_buf
);
2592 if (startswith (own_buf
, "qSearch:memory:"))
2594 require_running_or_return (own_buf
);
2595 handle_search_memory (own_buf
, packet_len
);
2599 if (strcmp (own_buf
, "qAttached") == 0
2600 || startswith (own_buf
, "qAttached:"))
2602 struct process_info
*process
;
2604 if (own_buf
[sizeof ("qAttached") - 1])
2606 int pid
= strtoul (own_buf
+ sizeof ("qAttached:") - 1, NULL
, 16);
2607 process
= find_process_pid (pid
);
2611 require_running_or_return (own_buf
);
2612 process
= current_process ();
2615 if (process
== NULL
)
2617 write_enn (own_buf
);
2621 strcpy (own_buf
, process
->attached
? "1" : "0");
2625 if (startswith (own_buf
, "qCRC:"))
2627 /* CRC check (compare-section). */
2631 unsigned long long crc
;
2633 require_running_or_return (own_buf
);
2634 comma
= unpack_varlen_hex (own_buf
+ 5, &base
);
2635 if (*comma
++ != ',')
2637 write_enn (own_buf
);
2640 len
= strtoul (comma
, NULL
, 16);
2641 crc
= crc32 (base
, len
, 0xffffffff);
2642 /* Check for memory failure. */
2643 if (crc
== (unsigned long long) -1)
2645 write_enn (own_buf
);
2648 sprintf (own_buf
, "C%lx", (unsigned long) crc
);
2652 if (handle_qxfer (own_buf
, packet_len
, new_packet_len_p
))
2655 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf
))
2658 /* Otherwise we didn't know what packet it was. Say we didn't
2663 static void gdb_wants_all_threads_stopped (void);
2664 static void resume (struct thread_resume
*actions
, size_t n
);
2666 /* The callback that is passed to visit_actioned_threads. */
2667 typedef int (visit_actioned_threads_callback_ftype
)
2668 (const struct thread_resume
*, struct thread_info
*);
2670 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
2671 true if CALLBACK returns true. Returns false if no matching thread
2672 is found or CALLBACK results false.
2673 Note: This function is itself a callback for find_thread. */
2676 visit_actioned_threads (thread_info
*thread
,
2677 const struct thread_resume
*actions
,
2679 visit_actioned_threads_callback_ftype
*callback
)
2681 for (size_t i
= 0; i
< num_actions
; i
++)
2683 const struct thread_resume
*action
= &actions
[i
];
2685 if (action
->thread
== minus_one_ptid
2686 || action
->thread
== thread
->id
2687 || ((action
->thread
.pid ()
2688 == thread
->id
.pid ())
2689 && action
->thread
.lwp () == -1))
2691 if ((*callback
) (action
, thread
))
2699 /* Callback for visit_actioned_threads. If the thread has a pending
2700 status to report, report it now. */
2703 handle_pending_status (const struct thread_resume
*resumption
,
2704 struct thread_info
*thread
)
2706 client_state
&cs
= get_client_state ();
2707 if (thread
->status_pending_p
)
2709 thread
->status_pending_p
= 0;
2711 cs
.last_status
= thread
->last_status
;
2712 cs
.last_ptid
= thread
->id
;
2713 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, &cs
.last_status
);
2719 /* Parse vCont packets. */
2721 handle_v_cont (char *own_buf
)
2725 struct thread_resume
*resume_info
;
2726 struct thread_resume default_action
{ null_ptid
};
2728 /* Count the number of semicolons in the packet. There should be one
2729 for every action. */
2735 p
= strchr (p
, ';');
2738 resume_info
= (struct thread_resume
*) malloc (n
* sizeof (resume_info
[0]));
2739 if (resume_info
== NULL
)
2747 memset (&resume_info
[i
], 0, sizeof resume_info
[i
]);
2749 if (p
[0] == 's' || p
[0] == 'S')
2750 resume_info
[i
].kind
= resume_step
;
2751 else if (p
[0] == 'r')
2752 resume_info
[i
].kind
= resume_step
;
2753 else if (p
[0] == 'c' || p
[0] == 'C')
2754 resume_info
[i
].kind
= resume_continue
;
2755 else if (p
[0] == 't')
2756 resume_info
[i
].kind
= resume_stop
;
2760 if (p
[0] == 'S' || p
[0] == 'C')
2763 int sig
= strtol (p
+ 1, &q
, 16);
2768 if (!gdb_signal_to_host_p ((enum gdb_signal
) sig
))
2770 resume_info
[i
].sig
= gdb_signal_to_host ((enum gdb_signal
) sig
);
2772 else if (p
[0] == 'r')
2776 p
= unpack_varlen_hex (p
+ 1, &addr
);
2777 resume_info
[i
].step_range_start
= addr
;
2782 p
= unpack_varlen_hex (p
+ 1, &addr
);
2783 resume_info
[i
].step_range_end
= addr
;
2792 resume_info
[i
].thread
= minus_one_ptid
;
2793 default_action
= resume_info
[i
];
2795 /* Note: we don't increment i here, we'll overwrite this entry
2796 the next time through. */
2798 else if (p
[0] == ':')
2801 ptid_t ptid
= read_ptid (p
+ 1, &q
);
2806 if (p
[0] != ';' && p
[0] != 0)
2809 resume_info
[i
].thread
= ptid
;
2816 resume_info
[i
] = default_action
;
2818 resume (resume_info
, n
);
2823 write_enn (own_buf
);
2828 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
2831 resume (struct thread_resume
*actions
, size_t num_actions
)
2833 client_state
&cs
= get_client_state ();
2836 /* Check if among the threads that GDB wants actioned, there's
2837 one with a pending status to report. If so, skip actually
2838 resuming/stopping and report the pending event
2841 thread_info
*thread_with_status
= find_thread ([&] (thread_info
*thread
)
2843 return visit_actioned_threads (thread
, actions
, num_actions
,
2844 handle_pending_status
);
2847 if (thread_with_status
!= NULL
)
2853 (*the_target
->resume
) (actions
, num_actions
);
2856 write_ok (cs
.own_buf
);
2859 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
, 0, 1);
2861 if (cs
.last_status
.kind
== TARGET_WAITKIND_NO_RESUMED
2862 && !report_no_resumed
)
2864 /* The client does not support this stop reply. At least
2866 sprintf (cs
.own_buf
, "E.No unwaited-for children left.");
2867 disable_async_io ();
2871 if (cs
.last_status
.kind
!= TARGET_WAITKIND_EXITED
2872 && cs
.last_status
.kind
!= TARGET_WAITKIND_SIGNALLED
2873 && cs
.last_status
.kind
!= TARGET_WAITKIND_NO_RESUMED
)
2874 current_thread
->last_status
= cs
.last_status
;
2876 /* From the client's perspective, all-stop mode always stops all
2877 threads implicitly (and the target backend has already done
2878 so by now). Tag all threads as "want-stopped", so we don't
2879 resume them implicitly without the client telling us to. */
2880 gdb_wants_all_threads_stopped ();
2881 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, &cs
.last_status
);
2882 disable_async_io ();
2884 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
2885 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
2886 target_mourn_inferior (cs
.last_ptid
);
2890 /* Attach to a new program. Return 1 if successful, 0 if failure. */
2892 handle_v_attach (char *own_buf
)
2894 client_state
&cs
= get_client_state ();
2897 pid
= strtol (own_buf
+ 8, NULL
, 16);
2898 if (pid
!= 0 && attach_inferior (pid
) == 0)
2900 /* Don't report shared library events after attaching, even if
2901 some libraries are preloaded. GDB will always poll the
2902 library list. Avoids the "stopped by shared library event"
2903 notice on the GDB side. */
2908 /* In non-stop, we don't send a resume reply. Stop events
2909 will follow up using the normal notification
2914 prepare_resume_reply (own_buf
, cs
.last_ptid
, &cs
.last_status
);
2920 write_enn (own_buf
);
2925 /* Run a new program. Return 1 if successful, 0 if failure. */
2927 handle_v_run (char *own_buf
)
2929 client_state
&cs
= get_client_state ();
2931 std::vector
<char *> new_argv
;
2932 char *new_program_name
= NULL
;
2936 for (p
= own_buf
+ strlen ("vRun;"); p
&& *p
; p
= strchr (p
, ';'))
2942 for (i
= 0, p
= own_buf
+ strlen ("vRun;"); *p
; p
= next_p
, ++i
)
2944 next_p
= strchr (p
, ';');
2946 next_p
= p
+ strlen (p
);
2948 if (i
== 0 && p
== next_p
)
2950 /* No program specified. */
2951 new_program_name
= NULL
;
2953 else if (p
== next_p
)
2955 /* Empty argument. */
2956 new_argv
.push_back (xstrdup ("''"));
2960 size_t len
= (next_p
- p
) / 2;
2961 /* ARG is the unquoted argument received via the RSP. */
2962 char *arg
= (char *) xmalloc (len
+ 1);
2963 /* FULL_ARGS will contain the quoted version of ARG. */
2964 char *full_arg
= (char *) xmalloc ((len
+ 1) * 2);
2965 /* These are pointers used to navigate the strings above. */
2966 char *tmp_arg
= arg
;
2967 char *tmp_full_arg
= full_arg
;
2970 hex2bin (p
, (gdb_byte
*) arg
, len
);
2973 while (*tmp_arg
!= '\0')
2979 *tmp_full_arg
= '\'';
2985 /* Quote single quote. */
2986 *tmp_full_arg
= '\\';
2994 *tmp_full_arg
= *tmp_arg
;
3000 *tmp_full_arg
++ = '\'';
3002 /* Finish FULL_ARG and push it into the vector containing
3004 *tmp_full_arg
= '\0';
3006 new_program_name
= full_arg
;
3008 new_argv
.push_back (full_arg
);
3014 new_argv
.push_back (NULL
);
3016 if (new_program_name
== NULL
)
3018 /* GDB didn't specify a program to run. Use the program from the
3019 last run with the new argument list. */
3020 if (program_path
.get () == NULL
)
3022 write_enn (own_buf
);
3023 free_vector_argv (new_argv
);
3028 program_path
.set (gdb::unique_xmalloc_ptr
<char> (new_program_name
));
3030 /* Free the old argv and install the new one. */
3031 free_vector_argv (program_args
);
3032 program_args
= new_argv
;
3034 create_inferior (program_path
.get (), program_args
);
3036 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
3038 prepare_resume_reply (own_buf
, cs
.last_ptid
, &cs
.last_status
);
3040 /* In non-stop, sending a resume reply doesn't set the general
3041 thread, but GDB assumes a vRun sets it (this is so GDB can
3042 query which is the main thread of the new inferior. */
3044 cs
.general_thread
= cs
.last_ptid
;
3050 write_enn (own_buf
);
3055 /* Kill process. Return 1 if successful, 0 if failure. */
3057 handle_v_kill (char *own_buf
)
3059 client_state
&cs
= get_client_state ();
3061 char *p
= &own_buf
[6];
3062 if (cs
.multi_process
)
3063 pid
= strtol (p
, NULL
, 16);
3067 process_info
*proc
= find_process_pid (pid
);
3069 if (proc
!= nullptr && kill_inferior (proc
) == 0)
3071 cs
.last_status
.kind
= TARGET_WAITKIND_SIGNALLED
;
3072 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
3073 cs
.last_ptid
= ptid_t (pid
);
3074 discard_queued_stop_replies (cs
.last_ptid
);
3080 write_enn (own_buf
);
3085 /* Handle all of the extended 'v' packets. */
3087 handle_v_requests (char *own_buf
, int packet_len
, int *new_packet_len
)
3089 client_state
&cs
= get_client_state ();
3090 if (!disable_packet_vCont
)
3092 if (strcmp (own_buf
, "vCtrlC") == 0)
3094 (*the_target
->request_interrupt
) ();
3099 if (startswith (own_buf
, "vCont;"))
3101 handle_v_cont (own_buf
);
3105 if (startswith (own_buf
, "vCont?"))
3107 strcpy (own_buf
, "vCont;c;C;t");
3109 if (target_supports_hardware_single_step ()
3110 || target_supports_software_single_step ()
3111 || !cs
.vCont_supported
)
3113 /* If target supports single step either by hardware or by
3114 software, add actions s and S to the list of supported
3115 actions. On the other hand, if GDB doesn't request the
3116 supported vCont actions in qSupported packet, add s and
3117 S to the list too. */
3118 own_buf
= own_buf
+ strlen (own_buf
);
3119 strcpy (own_buf
, ";s;S");
3122 if (target_supports_range_stepping ())
3124 own_buf
= own_buf
+ strlen (own_buf
);
3125 strcpy (own_buf
, ";r");
3131 if (startswith (own_buf
, "vFile:")
3132 && handle_vFile (own_buf
, packet_len
, new_packet_len
))
3135 if (startswith (own_buf
, "vAttach;"))
3137 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3139 fprintf (stderr
, "Already debugging a process\n");
3140 write_enn (own_buf
);
3143 handle_v_attach (own_buf
);
3147 if (startswith (own_buf
, "vRun;"))
3149 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3151 fprintf (stderr
, "Already debugging a process\n");
3152 write_enn (own_buf
);
3155 handle_v_run (own_buf
);
3159 if (startswith (own_buf
, "vKill;"))
3161 if (!target_running ())
3163 fprintf (stderr
, "No process to kill\n");
3164 write_enn (own_buf
);
3167 handle_v_kill (own_buf
);
3171 if (handle_notif_ack (own_buf
, packet_len
))
3174 /* Otherwise we didn't know what packet it was. Say we didn't
3180 /* Resume thread and wait for another event. In non-stop mode,
3181 don't really wait here, but return immediatelly to the event
3184 myresume (char *own_buf
, int step
, int sig
)
3186 client_state
&cs
= get_client_state ();
3187 struct thread_resume resume_info
[2];
3189 int valid_cont_thread
;
3191 valid_cont_thread
= (cs
.cont_thread
!= null_ptid
3192 && cs
.cont_thread
!= minus_one_ptid
);
3194 if (step
|| sig
|| valid_cont_thread
)
3196 resume_info
[0].thread
= current_ptid
;
3198 resume_info
[0].kind
= resume_step
;
3200 resume_info
[0].kind
= resume_continue
;
3201 resume_info
[0].sig
= sig
;
3205 if (!valid_cont_thread
)
3207 resume_info
[n
].thread
= minus_one_ptid
;
3208 resume_info
[n
].kind
= resume_continue
;
3209 resume_info
[n
].sig
= 0;
3213 resume (resume_info
, n
);
3216 /* Callback for for_each_thread. Make a new stop reply for each
3220 queue_stop_reply_callback (thread_info
*thread
)
3222 /* For now, assume targets that don't have this callback also don't
3223 manage the thread's last_status field. */
3224 if (the_target
->thread_stopped
== NULL
)
3226 struct vstop_notif
*new_notif
= new struct vstop_notif
;
3228 new_notif
->ptid
= thread
->id
;
3229 new_notif
->status
= thread
->last_status
;
3230 /* Pass the last stop reply back to GDB, but don't notify
3232 notif_event_enque (¬if_stop
, new_notif
);
3236 if (thread_stopped (thread
))
3240 std::string status_string
3241 = target_waitstatus_to_string (&thread
->last_status
);
3243 debug_printf ("Reporting thread %s as already stopped with %s\n",
3244 target_pid_to_str (thread
->id
),
3245 status_string
.c_str ());
3248 gdb_assert (thread
->last_status
.kind
!= TARGET_WAITKIND_IGNORE
);
3250 /* Pass the last stop reply back to GDB, but don't notify
3252 queue_stop_reply (thread
->id
, &thread
->last_status
);
3257 /* Set this inferior threads's state as "want-stopped". We won't
3258 resume this thread until the client gives us another action for
3262 gdb_wants_thread_stopped (thread_info
*thread
)
3264 thread
->last_resume_kind
= resume_stop
;
3266 if (thread
->last_status
.kind
== TARGET_WAITKIND_IGNORE
)
3268 /* Most threads are stopped implicitly (all-stop); tag that with
3270 thread
->last_status
.kind
= TARGET_WAITKIND_STOPPED
;
3271 thread
->last_status
.value
.sig
= GDB_SIGNAL_0
;
3275 /* Set all threads' states as "want-stopped". */
3278 gdb_wants_all_threads_stopped (void)
3280 for_each_thread (gdb_wants_thread_stopped
);
3283 /* Callback for for_each_thread. If the thread is stopped with an
3284 interesting event, mark it as having a pending event. */
3287 set_pending_status_callback (thread_info
*thread
)
3289 if (thread
->last_status
.kind
!= TARGET_WAITKIND_STOPPED
3290 || (thread
->last_status
.value
.sig
!= GDB_SIGNAL_0
3291 /* A breakpoint, watchpoint or finished step from a previous
3292 GDB run isn't considered interesting for a new GDB run.
3293 If we left those pending, the new GDB could consider them
3294 random SIGTRAPs. This leaves out real async traps. We'd
3295 have to peek into the (target-specific) siginfo to
3296 distinguish those. */
3297 && thread
->last_status
.value
.sig
!= GDB_SIGNAL_TRAP
))
3298 thread
->status_pending_p
= 1;
3301 /* Status handler for the '?' packet. */
3304 handle_status (char *own_buf
)
3306 client_state
&cs
= get_client_state ();
3308 /* GDB is connected, don't forward events to the target anymore. */
3309 for_each_process ([] (process_info
*process
) {
3310 process
->gdb_detached
= 0;
3313 /* In non-stop mode, we must send a stop reply for each stopped
3314 thread. In all-stop mode, just send one for the first stopped
3319 for_each_thread (queue_stop_reply_callback
);
3321 /* The first is sent immediatly. OK is sent if there is no
3322 stopped thread, which is the same handling of the vStopped
3323 packet (by design). */
3324 notif_write_event (¬if_stop
, cs
.own_buf
);
3328 thread_info
*thread
= NULL
;
3331 stabilize_threads ();
3332 gdb_wants_all_threads_stopped ();
3334 /* We can only report one status, but we might be coming out of
3335 non-stop -- if more than one thread is stopped with
3336 interesting events, leave events for the threads we're not
3337 reporting now pending. They'll be reported the next time the
3338 threads are resumed. Start by marking all interesting events
3340 for_each_thread (set_pending_status_callback
);
3342 /* Prefer the last thread that reported an event to GDB (even if
3343 that was a GDB_SIGNAL_TRAP). */
3344 if (cs
.last_status
.kind
!= TARGET_WAITKIND_IGNORE
3345 && cs
.last_status
.kind
!= TARGET_WAITKIND_EXITED
3346 && cs
.last_status
.kind
!= TARGET_WAITKIND_SIGNALLED
)
3347 thread
= find_thread_ptid (cs
.last_ptid
);
3349 /* If the last event thread is not found for some reason, look
3350 for some other thread that might have an event to report. */
3352 thread
= find_thread ([] (thread_info
*thr_arg
)
3354 return thr_arg
->status_pending_p
;
3357 /* If we're still out of luck, simply pick the first thread in
3360 thread
= get_first_thread ();
3364 struct thread_info
*tp
= (struct thread_info
*) thread
;
3366 /* We're reporting this event, so it's no longer
3368 tp
->status_pending_p
= 0;
3370 /* GDB assumes the current thread is the thread we're
3371 reporting the status for. */
3372 cs
.general_thread
= thread
->id
;
3373 set_desired_thread ();
3375 gdb_assert (tp
->last_status
.kind
!= TARGET_WAITKIND_IGNORE
);
3376 prepare_resume_reply (own_buf
, tp
->id
, &tp
->last_status
);
3379 strcpy (own_buf
, "W00");
3384 gdbserver_version (void)
3386 printf ("GNU gdbserver %s%s\n"
3387 "Copyright (C) 2019 Free Software Foundation, Inc.\n"
3388 "gdbserver is free software, covered by the "
3389 "GNU General Public License.\n"
3390 "This gdbserver was configured as \"%s\"\n",
3391 PKGVERSION
, version
, host_name
);
3395 gdbserver_usage (FILE *stream
)
3397 fprintf (stream
, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3398 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3399 "\tgdbserver [OPTIONS] --multi COMM\n"
3401 "COMM may either be a tty device (for serial debugging),\n"
3402 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3403 "stdin/stdout of gdbserver.\n"
3404 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3405 "PID is the process ID to attach to, when --attach is specified.\n"
3407 "Operating modes:\n"
3409 " --attach Attach to running process PID.\n"
3410 " --multi Start server without a specific program, and\n"
3411 " only quit when explicitly commanded.\n"
3412 " --once Exit after the first connection has closed.\n"
3413 " --help Print this message and then exit.\n"
3414 " --version Display version information and exit.\n"
3418 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3419 " --disable-randomization\n"
3420 " Run PROG with address space randomization disabled.\n"
3421 " --no-disable-randomization\n"
3422 " Don't disable address space randomization when\n"
3424 " --startup-with-shell\n"
3425 " Start PROG using a shell. I.e., execs a shell that\n"
3426 " then execs PROG. (default)\n"
3427 " --no-startup-with-shell\n"
3428 " Exec PROG directly instead of using a shell.\n"
3429 " Disables argument globbing and variable substitution\n"
3430 " on UNIX-like systems.\n"
3434 " --debug Enable general debugging output.\n"
3435 " --debug-format=OPT1[,OPT2,...]\n"
3436 " Specify extra content in debugging output.\n"
3441 " --remote-debug Enable remote protocol debugging output.\n"
3442 " --disable-packet=OPT1[,OPT2,...]\n"
3443 " Disable support for RSP packets or features.\n"
3445 " vCont, Tthread, qC, qfThreadInfo and \n"
3446 " threads (disable all threading packets).\n"
3448 "For more information, consult the GDB manual (available as on-line \n"
3449 "info or a printed manual).\n");
3450 if (REPORT_BUGS_TO
[0] && stream
== stdout
)
3451 fprintf (stream
, "Report bugs to \"%s\".\n", REPORT_BUGS_TO
);
3455 gdbserver_show_disableable (FILE *stream
)
3457 fprintf (stream
, "Disableable packets:\n"
3458 " vCont \tAll vCont packets\n"
3459 " qC \tQuerying the current thread\n"
3460 " qfThreadInfo\tThread listing\n"
3461 " Tthread \tPassing the thread specifier in the "
3462 "T stop reply packet\n"
3463 " threads \tAll of the above\n");
3467 kill_inferior_callback (process_info
*process
)
3469 kill_inferior (process
);
3470 discard_queued_stop_replies (ptid_t (process
->pid
));
3473 /* Call this when exiting gdbserver with possible inferiors that need
3474 to be killed or detached from. */
3477 detach_or_kill_for_exit (void)
3479 /* First print a list of the inferiors we will be killing/detaching.
3480 This is to assist the user, for example, in case the inferior unexpectedly
3481 dies after we exit: did we screw up or did the inferior exit on its own?
3482 Having this info will save some head-scratching. */
3484 if (have_started_inferiors_p ())
3486 fprintf (stderr
, "Killing process(es):");
3488 for_each_process ([] (process_info
*process
) {
3489 if (!process
->attached
)
3490 fprintf (stderr
, " %d", process
->pid
);
3493 fprintf (stderr
, "\n");
3495 if (have_attached_inferiors_p ())
3497 fprintf (stderr
, "Detaching process(es):");
3499 for_each_process ([] (process_info
*process
) {
3500 if (process
->attached
)
3501 fprintf (stderr
, " %d", process
->pid
);
3504 fprintf (stderr
, "\n");
3507 /* Now we can kill or detach the inferiors. */
3508 for_each_process ([] (process_info
*process
) {
3509 int pid
= process
->pid
;
3511 if (process
->attached
)
3512 detach_inferior (process
);
3514 kill_inferior (process
);
3516 discard_queued_stop_replies (ptid_t (pid
));
3520 /* Value that will be passed to exit(3) when gdbserver exits. */
3521 static int exit_code
;
3523 /* Wrapper for detach_or_kill_for_exit that catches and prints
3527 detach_or_kill_for_exit_cleanup ()
3531 detach_or_kill_for_exit ();
3533 catch (const gdb_exception
&exception
)
3536 fprintf (stderr
, "Detach or kill failed: %s\n",
3542 /* Main function. This is called by the real "main" function,
3543 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
3545 static void ATTRIBUTE_NORETURN
3546 captured_main (int argc
, char *argv
[])
3551 const char *port
= NULL
;
3552 char **next_arg
= &argv
[1];
3553 volatile int multi_mode
= 0;
3554 volatile int attach
= 0;
3556 bool selftest
= false;
3558 const char *selftest_filter
= NULL
;
3561 current_directory
= getcwd (NULL
, 0);
3562 client_state
&cs
= get_client_state ();
3564 if (current_directory
== NULL
)
3566 error (_("Could not find current working directory: %s"),
3567 safe_strerror (errno
));
3570 while (*next_arg
!= NULL
&& **next_arg
== '-')
3572 if (strcmp (*next_arg
, "--version") == 0)
3574 gdbserver_version ();
3577 else if (strcmp (*next_arg
, "--help") == 0)
3579 gdbserver_usage (stdout
);
3582 else if (strcmp (*next_arg
, "--attach") == 0)
3584 else if (strcmp (*next_arg
, "--multi") == 0)
3586 else if (strcmp (*next_arg
, "--wrapper") == 0)
3593 while (*next_arg
!= NULL
&& strcmp (*next_arg
, "--") != 0)
3595 wrapper_argv
+= *next_arg
;
3596 wrapper_argv
+= ' ';
3600 if (!wrapper_argv
.empty ())
3602 /* Erase the last whitespace. */
3603 wrapper_argv
.erase (wrapper_argv
.end () - 1);
3606 if (next_arg
== tmp
|| *next_arg
== NULL
)
3608 gdbserver_usage (stderr
);
3612 /* Consume the "--". */
3615 else if (strcmp (*next_arg
, "--debug") == 0)
3617 else if (startswith (*next_arg
, "--debug-format="))
3619 std::string error_msg
3620 = parse_debug_format_options ((*next_arg
)
3621 + sizeof ("--debug-format=") - 1, 0);
3623 if (!error_msg
.empty ())
3625 fprintf (stderr
, "%s", error_msg
.c_str ());
3629 else if (strcmp (*next_arg
, "--remote-debug") == 0)
3631 else if (startswith (*next_arg
, "--debug-file="))
3632 debug_set_output ((*next_arg
) + sizeof ("--debug-file=") -1);
3633 else if (strcmp (*next_arg
, "--disable-packet") == 0)
3635 gdbserver_show_disableable (stdout
);
3638 else if (startswith (*next_arg
, "--disable-packet="))
3640 char *packets
, *tok
;
3642 packets
= *next_arg
+= sizeof ("--disable-packet=") - 1;
3643 for (tok
= strtok (packets
, ",");
3645 tok
= strtok (NULL
, ","))
3647 if (strcmp ("vCont", tok
) == 0)
3648 disable_packet_vCont
= 1;
3649 else if (strcmp ("Tthread", tok
) == 0)
3650 disable_packet_Tthread
= 1;
3651 else if (strcmp ("qC", tok
) == 0)
3652 disable_packet_qC
= 1;
3653 else if (strcmp ("qfThreadInfo", tok
) == 0)
3654 disable_packet_qfThreadInfo
= 1;
3655 else if (strcmp ("threads", tok
) == 0)
3657 disable_packet_vCont
= 1;
3658 disable_packet_Tthread
= 1;
3659 disable_packet_qC
= 1;
3660 disable_packet_qfThreadInfo
= 1;
3664 fprintf (stderr
, "Don't know how to disable \"%s\".\n\n",
3666 gdbserver_show_disableable (stderr
);
3671 else if (strcmp (*next_arg
, "-") == 0)
3673 /* "-" specifies a stdio connection and is a form of port
3675 port
= STDIO_CONNECTION_NAME
;
3679 else if (strcmp (*next_arg
, "--disable-randomization") == 0)
3680 cs
.disable_randomization
= 1;
3681 else if (strcmp (*next_arg
, "--no-disable-randomization") == 0)
3682 cs
.disable_randomization
= 0;
3683 else if (strcmp (*next_arg
, "--startup-with-shell") == 0)
3684 startup_with_shell
= true;
3685 else if (strcmp (*next_arg
, "--no-startup-with-shell") == 0)
3686 startup_with_shell
= false;
3687 else if (strcmp (*next_arg
, "--once") == 0)
3689 else if (strcmp (*next_arg
, "--selftest") == 0)
3691 else if (startswith (*next_arg
, "--selftest="))
3695 selftest_filter
= *next_arg
+ strlen ("--selftest=");
3700 fprintf (stderr
, "Unknown argument: %s\n", *next_arg
);
3713 if ((port
== NULL
|| (!attach
&& !multi_mode
&& *next_arg
== NULL
))
3716 gdbserver_usage (stderr
);
3720 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
3721 opened by remote_prepare. */
3724 save_original_signals_state (false);
3726 /* We need to know whether the remote connection is stdio before
3727 starting the inferior. Inferiors created in this scenario have
3728 stdin,stdout redirected. So do this here before we call
3731 remote_prepare (port
);
3736 /* --attach used to come after PORT, so allow it there for
3738 if (*next_arg
!= NULL
&& strcmp (*next_arg
, "--attach") == 0)
3745 && (*next_arg
== NULL
3746 || (*next_arg
)[0] == '\0'
3747 || (pid
= strtoul (*next_arg
, &arg_end
, 0)) == 0
3749 || next_arg
[1] != NULL
))
3754 gdbserver_usage (stderr
);
3758 /* Gather information about the environment. */
3759 our_environ
= gdb_environ::from_host_environ ();
3761 initialize_async_io ();
3763 have_job_control ();
3764 initialize_event_loop ();
3765 if (target_supports_tracepoints ())
3766 initialize_tracepoint ();
3768 mem_buf
= (unsigned char *) xmalloc (PBUFSIZ
);
3773 selftests::run_tests (selftest_filter
);
3775 printf (_("Selftests have been disabled for this build.\n"));
3777 throw_quit ("Quit");
3780 if (pid
== 0 && *next_arg
!= NULL
)
3784 n
= argc
- (next_arg
- argv
);
3785 program_path
.set (make_unique_xstrdup (next_arg
[0]));
3786 for (i
= 1; i
< n
; i
++)
3787 program_args
.push_back (xstrdup (next_arg
[i
]));
3788 program_args
.push_back (NULL
);
3790 /* Wait till we are at first instruction in program. */
3791 create_inferior (program_path
.get (), program_args
);
3793 /* We are now (hopefully) stopped at the first instruction of
3794 the target process. This assumes that the target process was
3795 successfully created. */
3799 if (attach_inferior (pid
) == -1)
3800 error ("Attaching not supported on this target");
3802 /* Otherwise succeeded. */
3806 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
3807 cs
.last_status
.value
.integer
= 0;
3808 cs
.last_ptid
= minus_one_ptid
;
3811 SCOPE_EXIT
{ detach_or_kill_for_exit_cleanup (); };
3813 /* Don't report shared library events on the initial connection,
3814 even if some libraries are preloaded. Avoids the "stopped by
3815 shared library event" notice on gdb side. */
3818 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
3819 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
3824 if (!was_running
&& !multi_mode
)
3825 error ("No program to debug");
3830 cs
.multi_process
= 0;
3831 cs
.report_fork_events
= 0;
3832 cs
.report_vfork_events
= 0;
3833 cs
.report_exec_events
= 0;
3834 /* Be sure we're out of tfind mode. */
3835 cs
.current_traceframe
= -1;
3836 cs
.cont_thread
= null_ptid
;
3837 cs
.swbreak_feature
= 0;
3838 cs
.hwbreak_feature
= 0;
3839 cs
.vCont_supported
= 0;
3845 /* Wait for events. This will return when all event sources
3846 are removed from the event loop. */
3847 start_event_loop ();
3849 /* If an exit was requested (using the "monitor exit"
3850 command), terminate now. */
3852 throw_quit ("Quit");
3854 /* The only other way to get here is for getpkt to fail:
3856 - If --once was specified, we're done.
3858 - If not in extended-remote mode, and we're no longer
3859 debugging anything, simply exit: GDB has disconnected
3860 after processing the last process exit.
3862 - Otherwise, close the connection and reopen it at the
3864 if (run_once
|| (!extended_protocol
&& !target_running ()))
3865 throw_quit ("Quit");
3868 "Remote side has terminated connection. "
3869 "GDBserver will reopen the connection.\n");
3871 /* Get rid of any pending statuses. An eventual reconnection
3872 (by the same GDB instance or another) will refresh all its
3873 state from scratch. */
3874 discard_queued_stop_replies (minus_one_ptid
);
3875 for_each_thread ([] (thread_info
*thread
)
3877 thread
->status_pending_p
= 0;
3882 if (disconnected_tracing
)
3884 /* Try to enable non-stop/async mode, so we we can
3885 both wait for an async socket accept, and handle
3886 async target events simultaneously. There's also
3887 no point either in having the target always stop
3888 all threads, when we're going to pass signals
3889 down without informing GDB. */
3892 if (start_non_stop (1))
3895 /* Detaching implicitly resumes all threads;
3896 simply disconnecting does not. */
3902 "Disconnected tracing disabled; "
3903 "stopping trace run.\n");
3908 catch (const gdb_exception_error
&exception
)
3911 fprintf (stderr
, "gdbserver: %s\n", exception
.what ());
3913 if (response_needed
)
3915 write_enn (cs
.own_buf
);
3916 putpkt (cs
.own_buf
);
3920 throw_quit ("Quit");
3925 /* Main function. */
3928 main (int argc
, char *argv
[])
3933 captured_main (argc
, argv
);
3935 catch (const gdb_exception
&exception
)
3937 if (exception
.reason
== RETURN_ERROR
)
3940 fprintf (stderr
, "%s\n", exception
.what ());
3941 fprintf (stderr
, "Exiting\n");
3948 gdb_assert_not_reached ("captured_main should never return");
3951 /* Process options coming from Z packets for a breakpoint. PACKET is
3952 the packet buffer. *PACKET is updated to point to the first char
3953 after the last processed option. */
3956 process_point_options (struct gdb_breakpoint
*bp
, const char **packet
)
3958 const char *dataptr
= *packet
;
3961 /* Check if data has the correct format. */
3962 if (*dataptr
!= ';')
3969 if (*dataptr
== ';')
3972 if (*dataptr
== 'X')
3974 /* Conditional expression. */
3976 debug_printf ("Found breakpoint condition.\n");
3977 if (!add_breakpoint_condition (bp
, &dataptr
))
3978 dataptr
= strchrnul (dataptr
, ';');
3980 else if (startswith (dataptr
, "cmds:"))
3982 dataptr
+= strlen ("cmds:");
3984 debug_printf ("Found breakpoint commands %s.\n", dataptr
);
3985 persist
= (*dataptr
== '1');
3987 if (add_breakpoint_commands (bp
, &dataptr
, persist
))
3988 dataptr
= strchrnul (dataptr
, ';');
3992 fprintf (stderr
, "Unknown token %c, ignoring.\n",
3994 /* Skip tokens until we find one that we recognize. */
3995 dataptr
= strchrnul (dataptr
, ';');
4001 /* Event loop callback that handles a serial event. The first byte in
4002 the serial buffer gets us here. We expect characters to arrive at
4003 a brisk pace, so we read the rest of the packet with a blocking
4007 process_serial_event (void)
4009 client_state
&cs
= get_client_state ();
4015 int new_packet_len
= -1;
4017 disable_async_io ();
4019 response_needed
= 0;
4020 packet_len
= getpkt (cs
.own_buf
);
4021 if (packet_len
<= 0)
4024 /* Force an event loop break. */
4027 response_needed
= 1;
4029 char ch
= cs
.own_buf
[0];
4033 handle_query (cs
.own_buf
, packet_len
, &new_packet_len
);
4036 handle_general_set (cs
.own_buf
);
4039 handle_detach (cs
.own_buf
);
4042 extended_protocol
= 1;
4043 write_ok (cs
.own_buf
);
4046 handle_status (cs
.own_buf
);
4049 if (cs
.own_buf
[1] == 'c' || cs
.own_buf
[1] == 'g' || cs
.own_buf
[1] == 's')
4051 require_running_or_break (cs
.own_buf
);
4053 ptid_t thread_id
= read_ptid (&cs
.own_buf
[2], NULL
);
4055 if (thread_id
== null_ptid
|| thread_id
== minus_one_ptid
)
4056 thread_id
= null_ptid
;
4057 else if (thread_id
.is_pid ())
4059 /* The ptid represents a pid. */
4060 thread_info
*thread
= find_any_thread_of_pid (thread_id
.pid ());
4064 write_enn (cs
.own_buf
);
4068 thread_id
= thread
->id
;
4072 /* The ptid represents a lwp/tid. */
4073 if (find_thread_ptid (thread_id
) == NULL
)
4075 write_enn (cs
.own_buf
);
4080 if (cs
.own_buf
[1] == 'g')
4082 if (thread_id
== null_ptid
)
4084 /* GDB is telling us to choose any thread. Check if
4085 the currently selected thread is still valid. If
4086 it is not, select the first available. */
4087 thread_info
*thread
= find_thread_ptid (cs
.general_thread
);
4089 thread
= get_first_thread ();
4090 thread_id
= thread
->id
;
4093 cs
.general_thread
= thread_id
;
4094 set_desired_thread ();
4095 gdb_assert (current_thread
!= NULL
);
4097 else if (cs
.own_buf
[1] == 'c')
4098 cs
.cont_thread
= thread_id
;
4100 write_ok (cs
.own_buf
);
4104 /* Silently ignore it so that gdb can extend the protocol
4105 without compatibility headaches. */
4106 cs
.own_buf
[0] = '\0';
4110 require_running_or_break (cs
.own_buf
);
4111 if (cs
.current_traceframe
>= 0)
4113 struct regcache
*regcache
4114 = new_register_cache (current_target_desc ());
4116 if (fetch_traceframe_registers (cs
.current_traceframe
,
4118 registers_to_string (regcache
, cs
.own_buf
);
4120 write_enn (cs
.own_buf
);
4121 free_register_cache (regcache
);
4125 struct regcache
*regcache
;
4127 if (!set_desired_thread ())
4128 write_enn (cs
.own_buf
);
4131 regcache
= get_thread_regcache (current_thread
, 1);
4132 registers_to_string (regcache
, cs
.own_buf
);
4137 require_running_or_break (cs
.own_buf
);
4138 if (cs
.current_traceframe
>= 0)
4139 write_enn (cs
.own_buf
);
4142 struct regcache
*regcache
;
4144 if (!set_desired_thread ())
4145 write_enn (cs
.own_buf
);
4148 regcache
= get_thread_regcache (current_thread
, 1);
4149 registers_from_string (regcache
, &cs
.own_buf
[1]);
4150 write_ok (cs
.own_buf
);
4156 require_running_or_break (cs
.own_buf
);
4157 decode_m_packet (&cs
.own_buf
[1], &mem_addr
, &len
);
4158 int res
= gdb_read_memory (mem_addr
, mem_buf
, len
);
4160 write_enn (cs
.own_buf
);
4162 bin2hex (mem_buf
, cs
.own_buf
, res
);
4166 require_running_or_break (cs
.own_buf
);
4167 decode_M_packet (&cs
.own_buf
[1], &mem_addr
, &len
, &mem_buf
);
4168 if (gdb_write_memory (mem_addr
, mem_buf
, len
) == 0)
4169 write_ok (cs
.own_buf
);
4171 write_enn (cs
.own_buf
);
4174 require_running_or_break (cs
.own_buf
);
4175 if (decode_X_packet (&cs
.own_buf
[1], packet_len
- 1,
4176 &mem_addr
, &len
, &mem_buf
) < 0
4177 || gdb_write_memory (mem_addr
, mem_buf
, len
) != 0)
4178 write_enn (cs
.own_buf
);
4180 write_ok (cs
.own_buf
);
4183 require_running_or_break (cs
.own_buf
);
4184 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4185 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4186 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4189 myresume (cs
.own_buf
, 0, signal
);
4192 require_running_or_break (cs
.own_buf
);
4193 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4194 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4195 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4198 myresume (cs
.own_buf
, 1, signal
);
4201 require_running_or_break (cs
.own_buf
);
4203 myresume (cs
.own_buf
, 0, signal
);
4206 require_running_or_break (cs
.own_buf
);
4208 myresume (cs
.own_buf
, 1, signal
);
4210 case 'Z': /* insert_ ... */
4212 case 'z': /* remove_ ... */
4217 char type
= cs
.own_buf
[1];
4219 const int insert
= ch
== 'Z';
4220 const char *p
= &cs
.own_buf
[3];
4222 p
= unpack_varlen_hex (p
, &addr
);
4223 kind
= strtol (p
+ 1, &dataptr
, 16);
4227 struct gdb_breakpoint
*bp
;
4229 bp
= set_gdb_breakpoint (type
, addr
, kind
, &res
);
4234 /* GDB may have sent us a list of *point parameters to
4235 be evaluated on the target's side. Read such list
4236 here. If we already have a list of parameters, GDB
4237 is telling us to drop that list and use this one
4239 clear_breakpoint_conditions_and_commands (bp
);
4240 const char *options
= dataptr
;
4241 process_point_options (bp
, &options
);
4245 res
= delete_gdb_breakpoint (type
, addr
, kind
);
4248 write_ok (cs
.own_buf
);
4251 cs
.own_buf
[0] = '\0';
4253 write_enn (cs
.own_buf
);
4257 response_needed
= 0;
4258 if (!target_running ())
4259 /* The packet we received doesn't make sense - but we can't
4260 reply to it, either. */
4263 fprintf (stderr
, "Killing all inferiors\n");
4265 for_each_process (kill_inferior_callback
);
4267 /* When using the extended protocol, we wait with no program
4268 running. The traditional protocol will exit instead. */
4269 if (extended_protocol
)
4271 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
4272 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
4280 require_running_or_break (cs
.own_buf
);
4282 ptid_t thread_id
= read_ptid (&cs
.own_buf
[1], NULL
);
4283 if (find_thread_ptid (thread_id
) == NULL
)
4285 write_enn (cs
.own_buf
);
4289 if (mythread_alive (thread_id
))
4290 write_ok (cs
.own_buf
);
4292 write_enn (cs
.own_buf
);
4296 response_needed
= 0;
4298 /* Restarting the inferior is only supported in the extended
4300 if (extended_protocol
)
4302 if (target_running ())
4303 for_each_process (kill_inferior_callback
);
4305 fprintf (stderr
, "GDBserver restarting\n");
4307 /* Wait till we are at 1st instruction in prog. */
4308 if (program_path
.get () != NULL
)
4310 create_inferior (program_path
.get (), program_args
);
4312 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
4314 /* Stopped at the first instruction of the target
4316 cs
.general_thread
= cs
.last_ptid
;
4320 /* Something went wrong. */
4321 cs
.general_thread
= null_ptid
;
4326 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
4327 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
4333 /* It is a request we don't understand. Respond with an
4334 empty packet so that gdb knows that we don't support this
4336 cs
.own_buf
[0] = '\0';
4340 /* Extended (long) request. */
4341 handle_v_requests (cs
.own_buf
, packet_len
, &new_packet_len
);
4345 /* It is a request we don't understand. Respond with an empty
4346 packet so that gdb knows that we don't support this
4348 cs
.own_buf
[0] = '\0';
4352 if (new_packet_len
!= -1)
4353 putpkt_binary (cs
.own_buf
, new_packet_len
);
4355 putpkt (cs
.own_buf
);
4357 response_needed
= 0;
4365 /* Event-loop callback for serial events. */
4368 handle_serial_event (int err
, gdb_client_data client_data
)
4371 debug_printf ("handling possible serial event\n");
4373 /* Really handle it. */
4374 if (process_serial_event () < 0)
4377 /* Be sure to not change the selected thread behind GDB's back.
4378 Important in the non-stop mode asynchronous protocol. */
4379 set_desired_thread ();
4384 /* Push a stop notification on the notification queue. */
4387 push_stop_notification (ptid_t ptid
, struct target_waitstatus
*status
)
4389 struct vstop_notif
*vstop_notif
= new struct vstop_notif
;
4391 vstop_notif
->status
= *status
;
4392 vstop_notif
->ptid
= ptid
;
4393 /* Push Stop notification. */
4394 notif_push (¬if_stop
, vstop_notif
);
4397 /* Event-loop callback for target events. */
4400 handle_target_event (int err
, gdb_client_data client_data
)
4402 client_state
&cs
= get_client_state ();
4404 debug_printf ("handling possible target event\n");
4406 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
,
4409 if (cs
.last_status
.kind
== TARGET_WAITKIND_NO_RESUMED
)
4411 if (gdb_connected () && report_no_resumed
)
4412 push_stop_notification (null_ptid
, &cs
.last_status
);
4414 else if (cs
.last_status
.kind
!= TARGET_WAITKIND_IGNORE
)
4416 int pid
= cs
.last_ptid
.pid ();
4417 struct process_info
*process
= find_process_pid (pid
);
4418 int forward_event
= !gdb_connected () || process
->gdb_detached
;
4420 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
4421 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
4423 mark_breakpoints_out (process
);
4424 target_mourn_inferior (cs
.last_ptid
);
4426 else if (cs
.last_status
.kind
== TARGET_WAITKIND_THREAD_EXITED
)
4430 /* We're reporting this thread as stopped. Update its
4431 "want-stopped" state to what the client wants, until it
4432 gets a new resume action. */
4433 current_thread
->last_resume_kind
= resume_stop
;
4434 current_thread
->last_status
= cs
.last_status
;
4439 if (!target_running ())
4441 /* The last process exited. We're done. */
4445 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
4446 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
4447 || cs
.last_status
.kind
== TARGET_WAITKIND_THREAD_EXITED
)
4451 /* A thread stopped with a signal, but gdb isn't
4452 connected to handle it. Pass it down to the
4453 inferior, as if it wasn't being traced. */
4454 enum gdb_signal signal
;
4457 debug_printf ("GDB not connected; forwarding event %d for"
4459 (int) cs
.last_status
.kind
,
4460 target_pid_to_str (cs
.last_ptid
));
4462 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
4463 signal
= cs
.last_status
.value
.sig
;
4465 signal
= GDB_SIGNAL_0
;
4466 target_continue (cs
.last_ptid
, signal
);
4470 push_stop_notification (cs
.last_ptid
, &cs
.last_status
);
4473 /* Be sure to not change the selected thread behind GDB's back.
4474 Important in the non-stop mode asynchronous protocol. */
4475 set_desired_thread ();
4488 } // namespace selftests
4489 #endif /* GDB_SELF_TEST */