1 /* Main code for remote server for GDB.
2 Copyright (C) 1989-2020 Free Software Foundation, Inc.
4 This file is part of GDB.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #include "gdbthread.h"
21 #include "gdbsupport/agent.h"
24 #include "gdbsupport/rsp-low.h"
25 #include "gdbsupport/signals-state-save-restore.h"
31 #include "gdbsupport/gdb_vecs.h"
32 #include "gdbsupport/gdb_wait.h"
33 #include "gdbsupport/btrace-common.h"
34 #include "gdbsupport/filestuff.h"
35 #include "tracepoint.h"
39 #include "gdbsupport/common-inferior.h"
40 #include "gdbsupport/job-control.h"
41 #include "gdbsupport/environ.h"
42 #include "filenames.h"
43 #include "gdbsupport/pathstuff.h"
45 #include "xml-builtin.h"
48 #include "gdbsupport/selftest.h"
49 #include "gdbsupport/scope-exit.h"
51 #define require_running_or_return(BUF) \
52 if (!target_running ()) \
58 #define require_running_or_break(BUF) \
59 if (!target_running ()) \
65 /* String containing the current directory (what getwd would return). */
67 char *current_directory
;
69 /* The environment to pass to the inferior when creating it. */
71 static gdb_environ our_environ
;
75 static bool extended_protocol
;
76 static bool response_needed
;
77 static bool exit_requested
;
79 /* --once: Exit after the first connection has closed. */
82 /* Whether to report TARGET_WAITKIND_NO_RESUMED events. */
83 static bool report_no_resumed
;
88 /* Set the PROGRAM_PATH. Here we adjust the path of the provided
90 void set (gdb::unique_xmalloc_ptr
<char> &&path
)
92 m_path
= std::move (path
);
94 /* Make sure we're using the absolute path of the inferior when
96 if (!contains_dir_separator (m_path
.get ()))
100 /* Check if the file is in our CWD. If it is, then we prefix
101 its name with CURRENT_DIRECTORY. Otherwise, we leave the
102 name as-is because we'll try searching for it in $PATH. */
103 if (is_regular_file (m_path
.get (), ®_file_errno
))
104 m_path
= gdb_abspath (m_path
.get ());
108 /* Return the PROGRAM_PATH. */
110 { return m_path
.get (); }
113 /* The program name, adjusted if needed. */
114 gdb::unique_xmalloc_ptr
<char> m_path
;
116 static std::vector
<char *> program_args
;
117 static std::string wrapper_argv
;
119 /* The PID of the originally created or attached inferior. Used to
120 send signals to the process when GDB sends us an asynchronous interrupt
121 (user hitting Control-C in the client), and to wait for the child to exit
122 when no longer debugging it. */
124 unsigned long signal_pid
;
126 /* Set if you want to disable optional thread related packets support
127 in gdbserver, for the sake of testing GDB against stubs that don't
129 bool disable_packet_vCont
;
130 bool disable_packet_Tthread
;
131 bool disable_packet_qC
;
132 bool disable_packet_qfThreadInfo
;
134 static unsigned char *mem_buf
;
136 /* A sub-class of 'struct notif_event' for stop, holding information
137 relative to a single stop reply. We keep a queue of these to
138 push to GDB in non-stop mode. */
140 struct vstop_notif
: public notif_event
142 /* Thread or process that got the event. */
146 struct target_waitstatus status
;
149 /* The current btrace configuration. This is gdbserver's mirror of GDB's
150 btrace configuration. */
151 static struct btrace_config current_btrace_conf
;
153 /* The client remote protocol state. */
155 static client_state g_client_state
;
160 client_state
&cs
= g_client_state
;
165 /* Put a stop reply to the stop reply queue. */
168 queue_stop_reply (ptid_t ptid
, struct target_waitstatus
*status
)
170 struct vstop_notif
*new_notif
= new struct vstop_notif
;
172 new_notif
->ptid
= ptid
;
173 new_notif
->status
= *status
;
175 notif_event_enque (¬if_stop
, new_notif
);
179 remove_all_on_match_ptid (struct notif_event
*event
, ptid_t filter_ptid
)
181 struct vstop_notif
*vstop_event
= (struct vstop_notif
*) event
;
183 return vstop_event
->ptid
.matches (filter_ptid
);
189 discard_queued_stop_replies (ptid_t ptid
)
191 std::list
<notif_event
*>::iterator iter
, next
, end
;
192 end
= notif_stop
.queue
.end ();
193 for (iter
= notif_stop
.queue
.begin (); iter
!= end
; iter
= next
)
198 if (remove_all_on_match_ptid (*iter
, ptid
))
201 notif_stop
.queue
.erase (iter
);
207 vstop_notif_reply (struct notif_event
*event
, char *own_buf
)
209 struct vstop_notif
*vstop
= (struct vstop_notif
*) event
;
211 prepare_resume_reply (own_buf
, vstop
->ptid
, &vstop
->status
);
214 /* Helper for in_queued_stop_replies. */
217 in_queued_stop_replies_ptid (struct notif_event
*event
, ptid_t filter_ptid
)
219 struct vstop_notif
*vstop_event
= (struct vstop_notif
*) event
;
221 if (vstop_event
->ptid
.matches (filter_ptid
))
224 /* Don't resume fork children that GDB does not know about yet. */
225 if ((vstop_event
->status
.kind
== TARGET_WAITKIND_FORKED
226 || vstop_event
->status
.kind
== TARGET_WAITKIND_VFORKED
)
227 && vstop_event
->status
.value
.related_pid
.matches (filter_ptid
))
236 in_queued_stop_replies (ptid_t ptid
)
238 for (notif_event
*event
: notif_stop
.queue
)
240 if (in_queued_stop_replies_ptid (event
, ptid
))
247 struct notif_server notif_stop
=
249 "vStopped", "Stop", {}, vstop_notif_reply
,
253 target_running (void)
255 return get_first_thread () != NULL
;
258 /* See gdbsupport/common-inferior.h. */
263 return !wrapper_argv
.empty () ? wrapper_argv
.c_str () : NULL
;
266 /* See gdbsupport/common-inferior.h. */
269 get_exec_file (int err
)
271 if (err
&& program_path
.get () == NULL
)
272 error (_("No executable file specified."));
274 return program_path
.get ();
286 attach_inferior (int pid
)
288 client_state
&cs
= get_client_state ();
289 /* myattach should return -1 if attaching is unsupported,
290 0 if it succeeded, and call error() otherwise. */
292 if (find_process_pid (pid
) != nullptr)
293 error ("Already attached to process %d\n", pid
);
295 if (myattach (pid
) != 0)
298 fprintf (stderr
, "Attached; pid = %d\n", pid
);
301 /* FIXME - It may be that we should get the SIGNAL_PID from the
302 attach function, so that it can be the main thread instead of
303 whichever we were told to attach to. */
308 cs
.last_ptid
= mywait (ptid_t (pid
), &cs
.last_status
, 0, 0);
310 /* GDB knows to ignore the first SIGSTOP after attaching to a running
311 process using the "attach" command, but this is different; it's
312 just using "target remote". Pretend it's just starting up. */
313 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
314 && cs
.last_status
.value
.sig
== GDB_SIGNAL_STOP
)
315 cs
.last_status
.value
.sig
= GDB_SIGNAL_TRAP
;
317 current_thread
->last_resume_kind
= resume_stop
;
318 current_thread
->last_status
= cs
.last_status
;
324 /* Decode a qXfer read request. Return 0 if everything looks OK,
328 decode_xfer_read (char *buf
, CORE_ADDR
*ofs
, unsigned int *len
)
330 /* After the read marker and annex, qXfer looks like a
331 traditional 'm' packet. */
332 decode_m_packet (buf
, ofs
, len
);
338 decode_xfer (char *buf
, char **object
, char **rw
, char **annex
, char **offset
)
340 /* Extract and NUL-terminate the object. */
342 while (*buf
&& *buf
!= ':')
348 /* Extract and NUL-terminate the read/write action. */
350 while (*buf
&& *buf
!= ':')
356 /* Extract and NUL-terminate the annex. */
358 while (*buf
&& *buf
!= ':')
368 /* Write the response to a successful qXfer read. Returns the
369 length of the (binary) data stored in BUF, corresponding
370 to as much of DATA/LEN as we could fit. IS_MORE controls
371 the first character of the response. */
373 write_qxfer_response (char *buf
, const gdb_byte
*data
, int len
, int is_more
)
382 return remote_escape_output (data
, len
, 1, (unsigned char *) buf
+ 1,
383 &out_len
, PBUFSIZ
- 2) + 1;
386 /* Handle btrace enabling in BTS format. */
389 handle_btrace_enable_bts (struct thread_info
*thread
)
391 if (thread
->btrace
!= NULL
)
392 error (_("Btrace already enabled."));
394 current_btrace_conf
.format
= BTRACE_FORMAT_BTS
;
395 thread
->btrace
= target_enable_btrace (thread
->id
, ¤t_btrace_conf
);
398 /* Handle btrace enabling in Intel Processor Trace format. */
401 handle_btrace_enable_pt (struct thread_info
*thread
)
403 if (thread
->btrace
!= NULL
)
404 error (_("Btrace already enabled."));
406 current_btrace_conf
.format
= BTRACE_FORMAT_PT
;
407 thread
->btrace
= target_enable_btrace (thread
->id
, ¤t_btrace_conf
);
410 /* Handle btrace disabling. */
413 handle_btrace_disable (struct thread_info
*thread
)
416 if (thread
->btrace
== NULL
)
417 error (_("Branch tracing not enabled."));
419 if (target_disable_btrace (thread
->btrace
) != 0)
420 error (_("Could not disable branch tracing."));
422 thread
->btrace
= NULL
;
425 /* Handle the "Qbtrace" packet. */
428 handle_btrace_general_set (char *own_buf
)
430 client_state
&cs
= get_client_state ();
431 struct thread_info
*thread
;
434 if (!startswith (own_buf
, "Qbtrace:"))
437 op
= own_buf
+ strlen ("Qbtrace:");
439 if (cs
.general_thread
== null_ptid
440 || cs
.general_thread
== minus_one_ptid
)
442 strcpy (own_buf
, "E.Must select a single thread.");
446 thread
= find_thread_ptid (cs
.general_thread
);
449 strcpy (own_buf
, "E.No such thread.");
455 if (strcmp (op
, "bts") == 0)
456 handle_btrace_enable_bts (thread
);
457 else if (strcmp (op
, "pt") == 0)
458 handle_btrace_enable_pt (thread
);
459 else if (strcmp (op
, "off") == 0)
460 handle_btrace_disable (thread
);
462 error (_("Bad Qbtrace operation. Use bts, pt, or off."));
466 catch (const gdb_exception_error
&exception
)
468 sprintf (own_buf
, "E.%s", exception
.what ());
474 /* Handle the "Qbtrace-conf" packet. */
477 handle_btrace_conf_general_set (char *own_buf
)
479 client_state
&cs
= get_client_state ();
480 struct thread_info
*thread
;
483 if (!startswith (own_buf
, "Qbtrace-conf:"))
486 op
= own_buf
+ strlen ("Qbtrace-conf:");
488 if (cs
.general_thread
== null_ptid
489 || cs
.general_thread
== minus_one_ptid
)
491 strcpy (own_buf
, "E.Must select a single thread.");
495 thread
= find_thread_ptid (cs
.general_thread
);
498 strcpy (own_buf
, "E.No such thread.");
502 if (startswith (op
, "bts:size="))
508 size
= strtoul (op
+ strlen ("bts:size="), &endp
, 16);
509 if (endp
== NULL
|| *endp
!= 0 || errno
!= 0 || size
> UINT_MAX
)
511 strcpy (own_buf
, "E.Bad size value.");
515 current_btrace_conf
.bts
.size
= (unsigned int) size
;
517 else if (strncmp (op
, "pt:size=", strlen ("pt:size=")) == 0)
523 size
= strtoul (op
+ strlen ("pt:size="), &endp
, 16);
524 if (endp
== NULL
|| *endp
!= 0 || errno
!= 0 || size
> UINT_MAX
)
526 strcpy (own_buf
, "E.Bad size value.");
530 current_btrace_conf
.pt
.size
= (unsigned int) size
;
534 strcpy (own_buf
, "E.Bad Qbtrace configuration option.");
542 /* Handle all of the extended 'Q' packets. */
545 handle_general_set (char *own_buf
)
547 client_state
&cs
= get_client_state ();
548 if (startswith (own_buf
, "QPassSignals:"))
550 int numsigs
= (int) GDB_SIGNAL_LAST
, i
;
551 const char *p
= own_buf
+ strlen ("QPassSignals:");
554 p
= decode_address_to_semicolon (&cursig
, p
);
555 for (i
= 0; i
< numsigs
; i
++)
559 cs
.pass_signals
[i
] = 1;
561 /* Keep looping, to clear the remaining signals. */
564 p
= decode_address_to_semicolon (&cursig
, p
);
567 cs
.pass_signals
[i
] = 0;
569 strcpy (own_buf
, "OK");
573 if (startswith (own_buf
, "QProgramSignals:"))
575 int numsigs
= (int) GDB_SIGNAL_LAST
, i
;
576 const char *p
= own_buf
+ strlen ("QProgramSignals:");
579 cs
.program_signals_p
= 1;
581 p
= decode_address_to_semicolon (&cursig
, p
);
582 for (i
= 0; i
< numsigs
; i
++)
586 cs
.program_signals
[i
] = 1;
588 /* Keep looping, to clear the remaining signals. */
591 p
= decode_address_to_semicolon (&cursig
, p
);
594 cs
.program_signals
[i
] = 0;
596 strcpy (own_buf
, "OK");
600 if (startswith (own_buf
, "QCatchSyscalls:"))
602 const char *p
= own_buf
+ sizeof ("QCatchSyscalls:") - 1;
605 struct process_info
*process
;
607 if (!target_running () || !target_supports_catch_syscall ())
613 if (strcmp (p
, "0") == 0)
615 else if (p
[0] == '1' && (p
[1] == ';' || p
[1] == '\0'))
619 fprintf (stderr
, "Unknown catch-syscalls mode requested: %s\n",
625 process
= current_process ();
626 process
->syscalls_to_catch
.clear ();
636 p
= decode_address_to_semicolon (&sysno
, p
);
637 process
->syscalls_to_catch
.push_back (sysno
);
641 process
->syscalls_to_catch
.push_back (ANY_SYSCALL
);
648 if (strcmp (own_buf
, "QEnvironmentReset") == 0)
650 our_environ
= gdb_environ::from_host_environ ();
656 if (startswith (own_buf
, "QEnvironmentHexEncoded:"))
658 const char *p
= own_buf
+ sizeof ("QEnvironmentHexEncoded:") - 1;
659 /* The final form of the environment variable. FINAL_VAR will
660 hold the 'VAR=VALUE' format. */
661 std::string final_var
= hex2str (p
);
662 std::string var_name
, var_value
;
666 debug_printf (_("[QEnvironmentHexEncoded received '%s']\n"), p
);
667 debug_printf (_("[Environment variable to be set: '%s']\n"),
672 size_t pos
= final_var
.find ('=');
673 if (pos
== std::string::npos
)
675 warning (_("Unexpected format for environment variable: '%s'"),
681 var_name
= final_var
.substr (0, pos
);
682 var_value
= final_var
.substr (pos
+ 1, std::string::npos
);
684 our_environ
.set (var_name
.c_str (), var_value
.c_str ());
690 if (startswith (own_buf
, "QEnvironmentUnset:"))
692 const char *p
= own_buf
+ sizeof ("QEnvironmentUnset:") - 1;
693 std::string varname
= hex2str (p
);
697 debug_printf (_("[QEnvironmentUnset received '%s']\n"), p
);
698 debug_printf (_("[Environment variable to be unset: '%s']\n"),
703 our_environ
.unset (varname
.c_str ());
709 if (strcmp (own_buf
, "QStartNoAckMode") == 0)
713 debug_printf ("[noack mode enabled]\n");
722 if (startswith (own_buf
, "QNonStop:"))
724 char *mode
= own_buf
+ 9;
728 if (strcmp (mode
, "0") == 0)
730 else if (strcmp (mode
, "1") == 0)
734 /* We don't know what this mode is, so complain to
736 fprintf (stderr
, "Unknown non-stop mode requested: %s\n",
742 req_str
= req
? "non-stop" : "all-stop";
743 if (the_target
->pt
->start_non_stop (req
== 1) != 0)
745 fprintf (stderr
, "Setting %s mode failed\n", req_str
);
750 non_stop
= (req
!= 0);
753 debug_printf ("[%s mode enabled]\n", req_str
);
759 if (startswith (own_buf
, "QDisableRandomization:"))
761 char *packet
= own_buf
+ strlen ("QDisableRandomization:");
764 unpack_varlen_hex (packet
, &setting
);
765 cs
.disable_randomization
= setting
;
769 debug_printf (cs
.disable_randomization
770 ? "[address space randomization disabled]\n"
771 : "[address space randomization enabled]\n");
778 if (target_supports_tracepoints ()
779 && handle_tracepoint_general_set (own_buf
))
782 if (startswith (own_buf
, "QAgent:"))
784 char *mode
= own_buf
+ strlen ("QAgent:");
787 if (strcmp (mode
, "0") == 0)
789 else if (strcmp (mode
, "1") == 0)
793 /* We don't know what this value is, so complain to GDB. */
794 sprintf (own_buf
, "E.Unknown QAgent value");
798 /* Update the flag. */
801 debug_printf ("[%s agent]\n", req
? "Enable" : "Disable");
806 if (handle_btrace_general_set (own_buf
))
809 if (handle_btrace_conf_general_set (own_buf
))
812 if (startswith (own_buf
, "QThreadEvents:"))
814 char *mode
= own_buf
+ strlen ("QThreadEvents:");
815 enum tribool req
= TRIBOOL_UNKNOWN
;
817 if (strcmp (mode
, "0") == 0)
819 else if (strcmp (mode
, "1") == 0)
823 /* We don't know what this mode is, so complain to GDB. */
824 sprintf (own_buf
, "E.Unknown thread-events mode requested: %s\n",
829 cs
.report_thread_events
= (req
== TRIBOOL_TRUE
);
833 const char *req_str
= cs
.report_thread_events
? "enabled" : "disabled";
835 debug_printf ("[thread events are now %s]\n", req_str
);
842 if (startswith (own_buf
, "QStartupWithShell:"))
844 const char *value
= own_buf
+ strlen ("QStartupWithShell:");
846 if (strcmp (value
, "1") == 0)
847 startup_with_shell
= true;
848 else if (strcmp (value
, "0") == 0)
849 startup_with_shell
= false;
853 fprintf (stderr
, "Unknown value to startup-with-shell: %s\n",
860 debug_printf (_("[Inferior will %s started with shell]"),
861 startup_with_shell
? "be" : "not be");
867 if (startswith (own_buf
, "QSetWorkingDir:"))
869 const char *p
= own_buf
+ strlen ("QSetWorkingDir:");
873 std::string path
= hex2str (p
);
875 set_inferior_cwd (path
.c_str ());
878 debug_printf (_("[Set the inferior's current directory to %s]\n"),
883 /* An empty argument means that we should clear out any
884 previously set cwd for the inferior. */
885 set_inferior_cwd (NULL
);
889 [Unset the inferior's current directory; will use gdbserver's cwd]\n"));
896 /* Otherwise we didn't know what packet it was. Say we didn't
902 get_features_xml (const char *annex
)
904 const struct target_desc
*desc
= current_target_desc ();
906 /* `desc->xmltarget' defines what to return when looking for the
907 "target.xml" file. Its contents can either be verbatim XML code
908 (prefixed with a '@') or else the name of the actual XML file to
909 be used in place of "target.xml".
911 This variable is set up from the auto-generated
912 init_registers_... routine for the current target. */
914 if (strcmp (annex
, "target.xml") == 0)
916 const char *ret
= tdesc_get_features_xml (desc
);
928 /* Look for the annex. */
929 for (i
= 0; xml_builtin
[i
][0] != NULL
; i
++)
930 if (strcmp (annex
, xml_builtin
[i
][0]) == 0)
933 if (xml_builtin
[i
][0] != NULL
)
934 return xml_builtin
[i
][1];
942 monitor_show_help (void)
944 monitor_output ("The following monitor commands are supported:\n");
945 monitor_output (" set debug <0|1>\n");
946 monitor_output (" Enable general debugging messages\n");
947 monitor_output (" set debug-hw-points <0|1>\n");
948 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
949 monitor_output (" set remote-debug <0|1>\n");
950 monitor_output (" Enable remote protocol debugging messages\n");
951 monitor_output (" set debug-format option1[,option2,...]\n");
952 monitor_output (" Add additional information to debugging messages\n");
953 monitor_output (" Options: all, none");
954 monitor_output (", timestamp");
955 monitor_output ("\n");
956 monitor_output (" exit\n");
957 monitor_output (" Quit GDBserver\n");
960 /* Read trace frame or inferior memory. Returns the number of bytes
961 actually read, zero when no further transfer is possible, and -1 on
962 error. Return of a positive value smaller than LEN does not
963 indicate there's no more to be read, only the end of the transfer.
964 E.g., when GDB reads memory from a traceframe, a first request may
965 be served from a memory block that does not cover the whole request
966 length. A following request gets the rest served from either
967 another block (of the same traceframe) or from the read-only
971 gdb_read_memory (CORE_ADDR memaddr
, unsigned char *myaddr
, int len
)
973 client_state
&cs
= get_client_state ();
976 if (cs
.current_traceframe
>= 0)
979 ULONGEST length
= len
;
981 if (traceframe_read_mem (cs
.current_traceframe
,
982 memaddr
, myaddr
, len
, &nbytes
))
984 /* Data read from trace buffer, we're done. */
987 if (!in_readonly_region (memaddr
, length
))
989 /* Otherwise we have a valid readonly case, fall through. */
990 /* (assume no half-trace half-real blocks for now) */
993 res
= prepare_to_access_memory ();
996 if (set_desired_thread ())
997 res
= read_inferior_memory (memaddr
, myaddr
, len
);
1000 done_accessing_memory ();
1002 return res
== 0 ? len
: -1;
1008 /* Write trace frame or inferior memory. Actually, writing to trace
1009 frames is forbidden. */
1012 gdb_write_memory (CORE_ADDR memaddr
, const unsigned char *myaddr
, int len
)
1014 client_state
&cs
= get_client_state ();
1015 if (cs
.current_traceframe
>= 0)
1021 ret
= prepare_to_access_memory ();
1024 if (set_desired_thread ())
1025 ret
= target_write_memory (memaddr
, myaddr
, len
);
1028 done_accessing_memory ();
1034 /* Subroutine of handle_search_memory to simplify it. */
1037 handle_search_memory_1 (CORE_ADDR start_addr
, CORE_ADDR search_space_len
,
1038 gdb_byte
*pattern
, unsigned pattern_len
,
1039 gdb_byte
*search_buf
,
1040 unsigned chunk_size
, unsigned search_buf_size
,
1041 CORE_ADDR
*found_addrp
)
1043 /* Prime the search buffer. */
1045 if (gdb_read_memory (start_addr
, search_buf
, search_buf_size
)
1048 warning ("Unable to access %ld bytes of target "
1049 "memory at 0x%lx, halting search.",
1050 (long) search_buf_size
, (long) start_addr
);
1054 /* Perform the search.
1056 The loop is kept simple by allocating [N + pattern-length - 1] bytes.
1057 When we've scanned N bytes we copy the trailing bytes to the start and
1058 read in another N bytes. */
1060 while (search_space_len
>= pattern_len
)
1062 gdb_byte
*found_ptr
;
1063 unsigned nr_search_bytes
= (search_space_len
< search_buf_size
1067 found_ptr
= (gdb_byte
*) memmem (search_buf
, nr_search_bytes
, pattern
,
1070 if (found_ptr
!= NULL
)
1072 CORE_ADDR found_addr
= start_addr
+ (found_ptr
- search_buf
);
1073 *found_addrp
= found_addr
;
1077 /* Not found in this chunk, skip to next chunk. */
1079 /* Don't let search_space_len wrap here, it's unsigned. */
1080 if (search_space_len
>= chunk_size
)
1081 search_space_len
-= chunk_size
;
1083 search_space_len
= 0;
1085 if (search_space_len
>= pattern_len
)
1087 unsigned keep_len
= search_buf_size
- chunk_size
;
1088 CORE_ADDR read_addr
= start_addr
+ chunk_size
+ keep_len
;
1091 /* Copy the trailing part of the previous iteration to the front
1092 of the buffer for the next iteration. */
1093 memcpy (search_buf
, search_buf
+ chunk_size
, keep_len
);
1095 nr_to_read
= (search_space_len
- keep_len
< chunk_size
1096 ? search_space_len
- keep_len
1099 if (gdb_read_memory (read_addr
, search_buf
+ keep_len
,
1100 nr_to_read
) != search_buf_size
)
1102 warning ("Unable to access %ld bytes of target memory "
1103 "at 0x%lx, halting search.",
1104 (long) nr_to_read
, (long) read_addr
);
1108 start_addr
+= chunk_size
;
1117 /* Handle qSearch:memory packets. */
1120 handle_search_memory (char *own_buf
, int packet_len
)
1122 CORE_ADDR start_addr
;
1123 CORE_ADDR search_space_len
;
1125 unsigned int pattern_len
;
1126 /* NOTE: also defined in find.c testcase. */
1127 #define SEARCH_CHUNK_SIZE 16000
1128 const unsigned chunk_size
= SEARCH_CHUNK_SIZE
;
1129 /* Buffer to hold memory contents for searching. */
1130 gdb_byte
*search_buf
;
1131 unsigned search_buf_size
;
1133 CORE_ADDR found_addr
;
1134 int cmd_name_len
= sizeof ("qSearch:memory:") - 1;
1136 pattern
= (gdb_byte
*) malloc (packet_len
);
1137 if (pattern
== NULL
)
1139 error ("Unable to allocate memory to perform the search");
1140 strcpy (own_buf
, "E00");
1143 if (decode_search_memory_packet (own_buf
+ cmd_name_len
,
1144 packet_len
- cmd_name_len
,
1145 &start_addr
, &search_space_len
,
1146 pattern
, &pattern_len
) < 0)
1149 error ("Error in parsing qSearch:memory packet");
1150 strcpy (own_buf
, "E00");
1154 search_buf_size
= chunk_size
+ pattern_len
- 1;
1156 /* No point in trying to allocate a buffer larger than the search space. */
1157 if (search_space_len
< search_buf_size
)
1158 search_buf_size
= search_space_len
;
1160 search_buf
= (gdb_byte
*) malloc (search_buf_size
);
1161 if (search_buf
== NULL
)
1164 error ("Unable to allocate memory to perform the search");
1165 strcpy (own_buf
, "E00");
1169 found
= handle_search_memory_1 (start_addr
, search_space_len
,
1170 pattern
, pattern_len
,
1171 search_buf
, chunk_size
, search_buf_size
,
1175 sprintf (own_buf
, "1,%lx", (long) found_addr
);
1176 else if (found
== 0)
1177 strcpy (own_buf
, "0");
1179 strcpy (own_buf
, "E00");
1185 /* Handle the "D" packet. */
1188 handle_detach (char *own_buf
)
1190 client_state
&cs
= get_client_state ();
1192 process_info
*process
;
1194 if (cs
.multi_process
)
1197 int pid
= strtol (&own_buf
[2], NULL
, 16);
1199 process
= find_process_pid (pid
);
1203 process
= (current_thread
!= nullptr
1204 ? get_thread_process (current_thread
)
1208 if (process
== NULL
)
1210 write_enn (own_buf
);
1214 if ((tracing
&& disconnected_tracing
) || any_persistent_commands (process
))
1216 if (tracing
&& disconnected_tracing
)
1218 "Disconnected tracing in effect, "
1219 "leaving gdbserver attached to the process\n");
1221 if (any_persistent_commands (process
))
1223 "Persistent commands are present, "
1224 "leaving gdbserver attached to the process\n");
1226 /* Make sure we're in non-stop/async mode, so we we can both
1227 wait for an async socket accept, and handle async target
1228 events simultaneously. There's also no point either in
1229 having the target stop all threads, when we're going to
1230 pass signals down without informing GDB. */
1234 debug_printf ("Forcing non-stop mode\n");
1237 the_target
->pt
->start_non_stop (true);
1240 process
->gdb_detached
= 1;
1242 /* Detaching implicitly resumes all threads. */
1243 target_continue_no_signal (minus_one_ptid
);
1249 fprintf (stderr
, "Detaching from process %d\n", process
->pid
);
1252 /* We'll need this after PROCESS has been destroyed. */
1253 int pid
= process
->pid
;
1255 if (detach_inferior (process
) != 0)
1256 write_enn (own_buf
);
1259 discard_queued_stop_replies (ptid_t (pid
));
1262 if (extended_protocol
|| target_running ())
1264 /* There is still at least one inferior remaining or
1265 we are in extended mode, so don't terminate gdbserver,
1266 and instead treat this like a normal program exit. */
1267 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
1268 cs
.last_status
.value
.integer
= 0;
1269 cs
.last_ptid
= ptid_t (pid
);
1271 current_thread
= NULL
;
1278 /* If we are attached, then we can exit. Otherwise, we
1279 need to hang around doing nothing, until the child is
1281 join_inferior (pid
);
1287 /* Parse options to --debug-format= and "monitor set debug-format".
1288 ARG is the text after "--debug-format=" or "monitor set debug-format".
1289 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1290 This triggers calls to monitor_output.
1291 The result is an empty string if all options were parsed ok, otherwise an
1292 error message which the caller must free.
1294 N.B. These commands affect all debug format settings, they are not
1295 cumulative. If a format is not specified, it is turned off.
1296 However, we don't go to extra trouble with things like
1297 "monitor set debug-format all,none,timestamp".
1298 Instead we just parse them one at a time, in order.
1300 The syntax for "monitor set debug" we support here is not identical
1301 to gdb's "set debug foo on|off" because we also use this function to
1302 parse "--debug-format=foo,bar". */
1305 parse_debug_format_options (const char *arg
, int is_monitor
)
1307 /* First turn all debug format options off. */
1308 debug_timestamp
= 0;
1310 /* First remove leading spaces, for "monitor set debug-format". */
1311 while (isspace (*arg
))
1314 std::vector
<gdb::unique_xmalloc_ptr
<char>> options
1315 = delim_string_to_char_ptr_vec (arg
, ',');
1317 for (const gdb::unique_xmalloc_ptr
<char> &option
: options
)
1319 if (strcmp (option
.get (), "all") == 0)
1321 debug_timestamp
= 1;
1323 monitor_output ("All extra debug format options enabled.\n");
1325 else if (strcmp (option
.get (), "none") == 0)
1327 debug_timestamp
= 0;
1329 monitor_output ("All extra debug format options disabled.\n");
1331 else if (strcmp (option
.get (), "timestamp") == 0)
1333 debug_timestamp
= 1;
1335 monitor_output ("Timestamps will be added to debug output.\n");
1337 else if (*option
== '\0')
1339 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1343 return string_printf ("Unknown debug-format argument: \"%s\"\n",
1347 return std::string ();
1350 /* Handle monitor commands not handled by target-specific handlers. */
1353 handle_monitor_command (char *mon
, char *own_buf
)
1355 if (strcmp (mon
, "set debug 1") == 0)
1358 monitor_output ("Debug output enabled.\n");
1360 else if (strcmp (mon
, "set debug 0") == 0)
1363 monitor_output ("Debug output disabled.\n");
1365 else if (strcmp (mon
, "set debug-hw-points 1") == 0)
1367 show_debug_regs
= 1;
1368 monitor_output ("H/W point debugging output enabled.\n");
1370 else if (strcmp (mon
, "set debug-hw-points 0") == 0)
1372 show_debug_regs
= 0;
1373 monitor_output ("H/W point debugging output disabled.\n");
1375 else if (strcmp (mon
, "set remote-debug 1") == 0)
1378 monitor_output ("Protocol debug output enabled.\n");
1380 else if (strcmp (mon
, "set remote-debug 0") == 0)
1383 monitor_output ("Protocol debug output disabled.\n");
1385 else if (startswith (mon
, "set debug-format "))
1387 std::string error_msg
1388 = parse_debug_format_options (mon
+ sizeof ("set debug-format ") - 1,
1391 if (!error_msg
.empty ())
1393 monitor_output (error_msg
.c_str ());
1394 monitor_show_help ();
1395 write_enn (own_buf
);
1398 else if (strcmp (mon
, "set debug-file") == 0)
1399 debug_set_output (nullptr);
1400 else if (startswith (mon
, "set debug-file "))
1401 debug_set_output (mon
+ sizeof ("set debug-file ") - 1);
1402 else if (strcmp (mon
, "help") == 0)
1403 monitor_show_help ();
1404 else if (strcmp (mon
, "exit") == 0)
1405 exit_requested
= true;
1408 monitor_output ("Unknown monitor command.\n\n");
1409 monitor_show_help ();
1410 write_enn (own_buf
);
1414 /* Associates a callback with each supported qXfer'able object. */
1418 /* The object this handler handles. */
1421 /* Request that the target transfer up to LEN 8-bit bytes of the
1422 target's OBJECT. The OFFSET, for a seekable object, specifies
1423 the starting point. The ANNEX can be used to provide additional
1424 data-specific information to the target.
1426 Return the number of bytes actually transfered, zero when no
1427 further transfer is possible, -1 on error, -2 when the transfer
1428 is not supported, and -3 on a verbose error message that should
1429 be preserved. Return of a positive value smaller than LEN does
1430 not indicate the end of the object, only the end of the transfer.
1432 One, and only one, of readbuf or writebuf must be non-NULL. */
1433 int (*xfer
) (const char *annex
,
1434 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1435 ULONGEST offset
, LONGEST len
);
1438 /* Handle qXfer:auxv:read. */
1441 handle_qxfer_auxv (const char *annex
,
1442 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1443 ULONGEST offset
, LONGEST len
)
1445 if (!the_target
->pt
->supports_read_auxv () || writebuf
!= NULL
)
1448 if (annex
[0] != '\0' || current_thread
== NULL
)
1451 return the_target
->pt
->read_auxv (offset
, readbuf
, len
);
1454 /* Handle qXfer:exec-file:read. */
1457 handle_qxfer_exec_file (const char *annex
,
1458 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1459 ULONGEST offset
, LONGEST len
)
1465 if (the_target
->pid_to_exec_file
== NULL
|| writebuf
!= NULL
)
1468 if (annex
[0] == '\0')
1470 if (current_thread
== NULL
)
1473 pid
= pid_of (current_thread
);
1477 annex
= unpack_varlen_hex (annex
, &pid
);
1478 if (annex
[0] != '\0')
1485 file
= (*the_target
->pid_to_exec_file
) (pid
);
1489 total_len
= strlen (file
);
1491 if (offset
> total_len
)
1494 if (offset
+ len
> total_len
)
1495 len
= total_len
- offset
;
1497 memcpy (readbuf
, file
+ offset
, len
);
1501 /* Handle qXfer:features:read. */
1504 handle_qxfer_features (const char *annex
,
1505 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1506 ULONGEST offset
, LONGEST len
)
1508 const char *document
;
1511 if (writebuf
!= NULL
)
1514 if (!target_running ())
1517 /* Grab the correct annex. */
1518 document
= get_features_xml (annex
);
1519 if (document
== NULL
)
1522 total_len
= strlen (document
);
1524 if (offset
> total_len
)
1527 if (offset
+ len
> total_len
)
1528 len
= total_len
- offset
;
1530 memcpy (readbuf
, document
+ offset
, len
);
1534 /* Handle qXfer:libraries:read. */
1537 handle_qxfer_libraries (const char *annex
,
1538 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1539 ULONGEST offset
, LONGEST len
)
1541 if (writebuf
!= NULL
)
1544 if (annex
[0] != '\0' || current_thread
== NULL
)
1547 std::string document
= "<library-list version=\"1.0\">\n";
1549 for (const dll_info
&dll
: all_dlls
)
1550 document
+= string_printf
1551 (" <library name=\"%s\"><segment address=\"0x%s\"/></library>\n",
1552 dll
.name
.c_str (), paddress (dll
.base_addr
));
1554 document
+= "</library-list>\n";
1556 if (offset
> document
.length ())
1559 if (offset
+ len
> document
.length ())
1560 len
= document
.length () - offset
;
1562 memcpy (readbuf
, &document
[offset
], len
);
1567 /* Handle qXfer:libraries-svr4:read. */
1570 handle_qxfer_libraries_svr4 (const char *annex
,
1571 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1572 ULONGEST offset
, LONGEST len
)
1574 if (writebuf
!= NULL
)
1577 if (current_thread
== NULL
|| the_target
->qxfer_libraries_svr4
== NULL
)
1580 return the_target
->qxfer_libraries_svr4 (annex
, readbuf
, writebuf
, offset
, len
);
1583 /* Handle qXfer:osadata:read. */
1586 handle_qxfer_osdata (const char *annex
,
1587 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1588 ULONGEST offset
, LONGEST len
)
1590 if (!the_target
->pt
->supports_qxfer_osdata () || writebuf
!= NULL
)
1593 return the_target
->pt
->qxfer_osdata (annex
, readbuf
, NULL
, offset
, len
);
1596 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1599 handle_qxfer_siginfo (const char *annex
,
1600 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1601 ULONGEST offset
, LONGEST len
)
1603 if (!the_target
->pt
->supports_qxfer_siginfo ())
1606 if (annex
[0] != '\0' || current_thread
== NULL
)
1609 return the_target
->pt
->qxfer_siginfo (annex
, readbuf
, writebuf
, offset
, len
);
1612 /* Handle qXfer:statictrace:read. */
1615 handle_qxfer_statictrace (const char *annex
,
1616 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1617 ULONGEST offset
, LONGEST len
)
1619 client_state
&cs
= get_client_state ();
1622 if (writebuf
!= NULL
)
1625 if (annex
[0] != '\0' || current_thread
== NULL
1626 || cs
.current_traceframe
== -1)
1629 if (traceframe_read_sdata (cs
.current_traceframe
, offset
,
1630 readbuf
, len
, &nbytes
))
1635 /* Helper for handle_qxfer_threads_proper.
1636 Emit the XML to describe the thread of INF. */
1639 handle_qxfer_threads_worker (thread_info
*thread
, struct buffer
*buffer
)
1641 ptid_t ptid
= ptid_of (thread
);
1643 int core
= target_core_of_thread (ptid
);
1645 const char *name
= target_thread_name (ptid
);
1648 bool handle_status
= target_thread_handle (ptid
, &handle
, &handle_len
);
1650 write_ptid (ptid_s
, ptid
);
1652 buffer_xml_printf (buffer
, "<thread id=\"%s\"", ptid_s
);
1656 sprintf (core_s
, "%d", core
);
1657 buffer_xml_printf (buffer
, " core=\"%s\"", core_s
);
1661 buffer_xml_printf (buffer
, " name=\"%s\"", name
);
1665 char *handle_s
= (char *) alloca (handle_len
* 2 + 1);
1666 bin2hex (handle
, handle_s
, handle_len
);
1667 buffer_xml_printf (buffer
, " handle=\"%s\"", handle_s
);
1670 buffer_xml_printf (buffer
, "/>\n");
1673 /* Helper for handle_qxfer_threads. */
1676 handle_qxfer_threads_proper (struct buffer
*buffer
)
1678 buffer_grow_str (buffer
, "<threads>\n");
1680 for_each_thread ([&] (thread_info
*thread
)
1682 handle_qxfer_threads_worker (thread
, buffer
);
1685 buffer_grow_str0 (buffer
, "</threads>\n");
1688 /* Handle qXfer:threads:read. */
1691 handle_qxfer_threads (const char *annex
,
1692 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1693 ULONGEST offset
, LONGEST len
)
1695 static char *result
= 0;
1696 static unsigned int result_length
= 0;
1698 if (writebuf
!= NULL
)
1701 if (annex
[0] != '\0')
1706 struct buffer buffer
;
1707 /* When asked for data at offset 0, generate everything and store into
1708 'result'. Successive reads will be served off 'result'. */
1712 buffer_init (&buffer
);
1714 handle_qxfer_threads_proper (&buffer
);
1716 result
= buffer_finish (&buffer
);
1717 result_length
= strlen (result
);
1718 buffer_free (&buffer
);
1721 if (offset
>= result_length
)
1723 /* We're out of data. */
1730 if (len
> result_length
- offset
)
1731 len
= result_length
- offset
;
1733 memcpy (readbuf
, result
+ offset
, len
);
1738 /* Handle qXfer:traceframe-info:read. */
1741 handle_qxfer_traceframe_info (const char *annex
,
1742 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1743 ULONGEST offset
, LONGEST len
)
1745 client_state
&cs
= get_client_state ();
1746 static char *result
= 0;
1747 static unsigned int result_length
= 0;
1749 if (writebuf
!= NULL
)
1752 if (!target_running () || annex
[0] != '\0' || cs
.current_traceframe
== -1)
1757 struct buffer buffer
;
1759 /* When asked for data at offset 0, generate everything and
1760 store into 'result'. Successive reads will be served off
1764 buffer_init (&buffer
);
1766 traceframe_read_info (cs
.current_traceframe
, &buffer
);
1768 result
= buffer_finish (&buffer
);
1769 result_length
= strlen (result
);
1770 buffer_free (&buffer
);
1773 if (offset
>= result_length
)
1775 /* We're out of data. */
1782 if (len
> result_length
- offset
)
1783 len
= result_length
- offset
;
1785 memcpy (readbuf
, result
+ offset
, len
);
1789 /* Handle qXfer:fdpic:read. */
1792 handle_qxfer_fdpic (const char *annex
, gdb_byte
*readbuf
,
1793 const gdb_byte
*writebuf
, ULONGEST offset
, LONGEST len
)
1795 if (!the_target
->pt
->supports_read_loadmap ())
1798 if (current_thread
== NULL
)
1801 return the_target
->pt
->read_loadmap (annex
, offset
, readbuf
, len
);
1804 /* Handle qXfer:btrace:read. */
1807 handle_qxfer_btrace (const char *annex
,
1808 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1809 ULONGEST offset
, LONGEST len
)
1811 client_state
&cs
= get_client_state ();
1812 static struct buffer cache
;
1813 struct thread_info
*thread
;
1814 enum btrace_read_type type
;
1817 if (writebuf
!= NULL
)
1820 if (cs
.general_thread
== null_ptid
1821 || cs
.general_thread
== minus_one_ptid
)
1823 strcpy (cs
.own_buf
, "E.Must select a single thread.");
1827 thread
= find_thread_ptid (cs
.general_thread
);
1830 strcpy (cs
.own_buf
, "E.No such thread.");
1834 if (thread
->btrace
== NULL
)
1836 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
1840 if (strcmp (annex
, "all") == 0)
1841 type
= BTRACE_READ_ALL
;
1842 else if (strcmp (annex
, "new") == 0)
1843 type
= BTRACE_READ_NEW
;
1844 else if (strcmp (annex
, "delta") == 0)
1845 type
= BTRACE_READ_DELTA
;
1848 strcpy (cs
.own_buf
, "E.Bad annex.");
1854 buffer_free (&cache
);
1858 result
= target_read_btrace (thread
->btrace
, &cache
, type
);
1860 memcpy (cs
.own_buf
, cache
.buffer
, cache
.used_size
);
1862 catch (const gdb_exception_error
&exception
)
1864 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
1871 else if (offset
> cache
.used_size
)
1873 buffer_free (&cache
);
1877 if (len
> cache
.used_size
- offset
)
1878 len
= cache
.used_size
- offset
;
1880 memcpy (readbuf
, cache
.buffer
+ offset
, len
);
1885 /* Handle qXfer:btrace-conf:read. */
1888 handle_qxfer_btrace_conf (const char *annex
,
1889 gdb_byte
*readbuf
, const gdb_byte
*writebuf
,
1890 ULONGEST offset
, LONGEST len
)
1892 client_state
&cs
= get_client_state ();
1893 static struct buffer cache
;
1894 struct thread_info
*thread
;
1897 if (writebuf
!= NULL
)
1900 if (annex
[0] != '\0')
1903 if (cs
.general_thread
== null_ptid
1904 || cs
.general_thread
== minus_one_ptid
)
1906 strcpy (cs
.own_buf
, "E.Must select a single thread.");
1910 thread
= find_thread_ptid (cs
.general_thread
);
1913 strcpy (cs
.own_buf
, "E.No such thread.");
1917 if (thread
->btrace
== NULL
)
1919 strcpy (cs
.own_buf
, "E.Btrace not enabled.");
1925 buffer_free (&cache
);
1929 result
= target_read_btrace_conf (thread
->btrace
, &cache
);
1931 memcpy (cs
.own_buf
, cache
.buffer
, cache
.used_size
);
1933 catch (const gdb_exception_error
&exception
)
1935 sprintf (cs
.own_buf
, "E.%s", exception
.what ());
1942 else if (offset
> cache
.used_size
)
1944 buffer_free (&cache
);
1948 if (len
> cache
.used_size
- offset
)
1949 len
= cache
.used_size
- offset
;
1951 memcpy (readbuf
, cache
.buffer
+ offset
, len
);
1956 static const struct qxfer qxfer_packets
[] =
1958 { "auxv", handle_qxfer_auxv
},
1959 { "btrace", handle_qxfer_btrace
},
1960 { "btrace-conf", handle_qxfer_btrace_conf
},
1961 { "exec-file", handle_qxfer_exec_file
},
1962 { "fdpic", handle_qxfer_fdpic
},
1963 { "features", handle_qxfer_features
},
1964 { "libraries", handle_qxfer_libraries
},
1965 { "libraries-svr4", handle_qxfer_libraries_svr4
},
1966 { "osdata", handle_qxfer_osdata
},
1967 { "siginfo", handle_qxfer_siginfo
},
1968 { "statictrace", handle_qxfer_statictrace
},
1969 { "threads", handle_qxfer_threads
},
1970 { "traceframe-info", handle_qxfer_traceframe_info
},
1974 handle_qxfer (char *own_buf
, int packet_len
, int *new_packet_len_p
)
1982 if (!startswith (own_buf
, "qXfer:"))
1985 /* Grab the object, r/w and annex. */
1986 if (decode_xfer (own_buf
+ 6, &object
, &rw
, &annex
, &offset
) < 0)
1988 write_enn (own_buf
);
1993 i
< sizeof (qxfer_packets
) / sizeof (qxfer_packets
[0]);
1996 const struct qxfer
*q
= &qxfer_packets
[i
];
1998 if (strcmp (object
, q
->object
) == 0)
2000 if (strcmp (rw
, "read") == 0)
2002 unsigned char *data
;
2007 /* Grab the offset and length. */
2008 if (decode_xfer_read (offset
, &ofs
, &len
) < 0)
2010 write_enn (own_buf
);
2014 /* Read one extra byte, as an indicator of whether there is
2016 if (len
> PBUFSIZ
- 2)
2018 data
= (unsigned char *) malloc (len
+ 1);
2021 write_enn (own_buf
);
2024 n
= (*q
->xfer
) (annex
, data
, NULL
, ofs
, len
+ 1);
2032 /* Preserve error message. */
2035 write_enn (own_buf
);
2037 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, len
, 1);
2039 *new_packet_len_p
= write_qxfer_response (own_buf
, data
, n
, 0);
2044 else if (strcmp (rw
, "write") == 0)
2049 unsigned char *data
;
2051 strcpy (own_buf
, "E00");
2052 data
= (unsigned char *) malloc (packet_len
- (offset
- own_buf
));
2055 write_enn (own_buf
);
2058 if (decode_xfer_write (offset
, packet_len
- (offset
- own_buf
),
2059 &ofs
, &len
, data
) < 0)
2062 write_enn (own_buf
);
2066 n
= (*q
->xfer
) (annex
, NULL
, data
, ofs
, len
);
2074 /* Preserve error message. */
2077 write_enn (own_buf
);
2079 sprintf (own_buf
, "%x", n
);
2092 /* Compute 32 bit CRC from inferior memory.
2094 On success, return 32 bit CRC.
2095 On failure, return (unsigned long long) -1. */
2097 static unsigned long long
2098 crc32 (CORE_ADDR base
, int len
, unsigned int crc
)
2102 unsigned char byte
= 0;
2104 /* Return failure if memory read fails. */
2105 if (read_inferior_memory (base
, &byte
, 1) != 0)
2106 return (unsigned long long) -1;
2108 crc
= xcrc32 (&byte
, 1, crc
);
2111 return (unsigned long long) crc
;
2114 /* Add supported btrace packets to BUF. */
2117 supported_btrace_packets (char *buf
)
2119 strcat (buf
, ";Qbtrace:bts+");
2120 strcat (buf
, ";Qbtrace-conf:bts:size+");
2121 strcat (buf
, ";Qbtrace:pt+");
2122 strcat (buf
, ";Qbtrace-conf:pt:size+");
2123 strcat (buf
, ";Qbtrace:off+");
2124 strcat (buf
, ";qXfer:btrace:read+");
2125 strcat (buf
, ";qXfer:btrace-conf:read+");
2128 /* Handle all of the extended 'q' packets. */
2131 handle_query (char *own_buf
, int packet_len
, int *new_packet_len_p
)
2133 client_state
&cs
= get_client_state ();
2134 static std::list
<thread_info
*>::const_iterator thread_iter
;
2136 /* Reply the current thread id. */
2137 if (strcmp ("qC", own_buf
) == 0 && !disable_packet_qC
)
2140 require_running_or_return (own_buf
);
2142 if (cs
.general_thread
!= null_ptid
&& cs
.general_thread
!= minus_one_ptid
)
2143 ptid
= cs
.general_thread
;
2146 thread_iter
= all_threads
.begin ();
2147 ptid
= (*thread_iter
)->id
;
2150 sprintf (own_buf
, "QC");
2152 write_ptid (own_buf
, ptid
);
2156 if (strcmp ("qSymbol::", own_buf
) == 0)
2158 struct thread_info
*save_thread
= current_thread
;
2160 /* For qSymbol, GDB only changes the current thread if the
2161 previous current thread was of a different process. So if
2162 the previous thread is gone, we need to pick another one of
2163 the same process. This can happen e.g., if we followed an
2164 exec in a non-leader thread. */
2165 if (current_thread
== NULL
)
2168 = find_any_thread_of_pid (cs
.general_thread
.pid ());
2170 /* Just in case, if we didn't find a thread, then bail out
2171 instead of crashing. */
2172 if (current_thread
== NULL
)
2174 write_enn (own_buf
);
2175 current_thread
= save_thread
;
2180 /* GDB is suggesting new symbols have been loaded. This may
2181 mean a new shared library has been detected as loaded, so
2182 take the opportunity to check if breakpoints we think are
2183 inserted, still are. Note that it isn't guaranteed that
2184 we'll see this when a shared library is loaded, and nor will
2185 we see this for unloads (although breakpoints in unloaded
2186 libraries shouldn't trigger), as GDB may not find symbols for
2187 the library at all. We also re-validate breakpoints when we
2188 see a second GDB breakpoint for the same address, and or when
2189 we access breakpoint shadows. */
2190 validate_breakpoints ();
2192 if (target_supports_tracepoints ())
2193 tracepoint_look_up_symbols ();
2195 if (current_thread
!= NULL
)
2196 the_target
->pt
->look_up_symbols ();
2198 current_thread
= save_thread
;
2200 strcpy (own_buf
, "OK");
2204 if (!disable_packet_qfThreadInfo
)
2206 if (strcmp ("qfThreadInfo", own_buf
) == 0)
2208 require_running_or_return (own_buf
);
2209 thread_iter
= all_threads
.begin ();
2212 ptid_t ptid
= (*thread_iter
)->id
;
2213 write_ptid (own_buf
, ptid
);
2218 if (strcmp ("qsThreadInfo", own_buf
) == 0)
2220 require_running_or_return (own_buf
);
2221 if (thread_iter
!= all_threads
.end ())
2224 ptid_t ptid
= (*thread_iter
)->id
;
2225 write_ptid (own_buf
, ptid
);
2231 sprintf (own_buf
, "l");
2237 if (the_target
->pt
->supports_read_offsets ()
2238 && strcmp ("qOffsets", own_buf
) == 0)
2240 CORE_ADDR text
, data
;
2242 require_running_or_return (own_buf
);
2243 if (the_target
->pt
->read_offsets (&text
, &data
))
2244 sprintf (own_buf
, "Text=%lX;Data=%lX;Bss=%lX",
2245 (long)text
, (long)data
, (long)data
);
2247 write_enn (own_buf
);
2252 /* Protocol features query. */
2253 if (startswith (own_buf
, "qSupported")
2254 && (own_buf
[10] == ':' || own_buf
[10] == '\0'))
2256 char *p
= &own_buf
[10];
2257 int gdb_supports_qRelocInsn
= 0;
2259 /* Process each feature being provided by GDB. The first
2260 feature will follow a ':', and latter features will follow
2264 char **qsupported
= NULL
;
2269 /* Two passes, to avoid nested strtok calls in
2270 target_process_qsupported. */
2272 for (p
= strtok_r (p
+ 1, ";", &saveptr
);
2274 p
= strtok_r (NULL
, ";", &saveptr
))
2277 qsupported
= XRESIZEVEC (char *, qsupported
, count
);
2278 qsupported
[count
- 1] = xstrdup (p
);
2281 for (i
= 0; i
< count
; i
++)
2284 if (strcmp (p
, "multiprocess+") == 0)
2286 /* GDB supports and wants multi-process support if
2288 if (target_supports_multi_process ())
2289 cs
.multi_process
= 1;
2291 else if (strcmp (p
, "qRelocInsn+") == 0)
2293 /* GDB supports relocate instruction requests. */
2294 gdb_supports_qRelocInsn
= 1;
2296 else if (strcmp (p
, "swbreak+") == 0)
2298 /* GDB wants us to report whether a trap is caused
2299 by a software breakpoint and for us to handle PC
2300 adjustment if necessary on this target. */
2301 if (target_supports_stopped_by_sw_breakpoint ())
2302 cs
.swbreak_feature
= 1;
2304 else if (strcmp (p
, "hwbreak+") == 0)
2306 /* GDB wants us to report whether a trap is caused
2307 by a hardware breakpoint. */
2308 if (target_supports_stopped_by_hw_breakpoint ())
2309 cs
.hwbreak_feature
= 1;
2311 else if (strcmp (p
, "fork-events+") == 0)
2313 /* GDB supports and wants fork events if possible. */
2314 if (target_supports_fork_events ())
2315 cs
.report_fork_events
= 1;
2317 else if (strcmp (p
, "vfork-events+") == 0)
2319 /* GDB supports and wants vfork events if possible. */
2320 if (target_supports_vfork_events ())
2321 cs
.report_vfork_events
= 1;
2323 else if (strcmp (p
, "exec-events+") == 0)
2325 /* GDB supports and wants exec events if possible. */
2326 if (target_supports_exec_events ())
2327 cs
.report_exec_events
= 1;
2329 else if (strcmp (p
, "vContSupported+") == 0)
2330 cs
.vCont_supported
= 1;
2331 else if (strcmp (p
, "QThreadEvents+") == 0)
2333 else if (strcmp (p
, "no-resumed+") == 0)
2335 /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
2337 report_no_resumed
= true;
2341 /* Move the unknown features all together. */
2342 qsupported
[i
] = NULL
;
2343 qsupported
[unknown
] = p
;
2348 /* Give the target backend a chance to process the unknown
2350 target_process_qsupported (qsupported
, unknown
);
2352 for (i
= 0; i
< count
; i
++)
2353 free (qsupported
[i
]);
2358 "PacketSize=%x;QPassSignals+;QProgramSignals+;"
2359 "QStartupWithShell+;QEnvironmentHexEncoded+;"
2360 "QEnvironmentReset+;QEnvironmentUnset+;"
2364 if (target_supports_catch_syscall ())
2365 strcat (own_buf
, ";QCatchSyscalls+");
2367 if (the_target
->qxfer_libraries_svr4
!= NULL
)
2368 strcat (own_buf
, ";qXfer:libraries-svr4:read+"
2369 ";augmented-libraries-svr4-read+");
2372 /* We do not have any hook to indicate whether the non-SVR4 target
2373 backend supports qXfer:libraries:read, so always report it. */
2374 strcat (own_buf
, ";qXfer:libraries:read+");
2377 if (the_target
->pt
->supports_read_auxv ())
2378 strcat (own_buf
, ";qXfer:auxv:read+");
2380 if (the_target
->pt
->supports_qxfer_siginfo ())
2381 strcat (own_buf
, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2383 if (the_target
->pt
->supports_read_loadmap ())
2384 strcat (own_buf
, ";qXfer:fdpic:read+");
2386 /* We always report qXfer:features:read, as targets may
2387 install XML files on a subsequent call to arch_setup.
2388 If we reported to GDB on startup that we don't support
2389 qXfer:feature:read at all, we will never be re-queried. */
2390 strcat (own_buf
, ";qXfer:features:read+");
2392 if (cs
.transport_is_reliable
)
2393 strcat (own_buf
, ";QStartNoAckMode+");
2395 if (the_target
->pt
->supports_qxfer_osdata ())
2396 strcat (own_buf
, ";qXfer:osdata:read+");
2398 if (target_supports_multi_process ())
2399 strcat (own_buf
, ";multiprocess+");
2401 if (target_supports_fork_events ())
2402 strcat (own_buf
, ";fork-events+");
2404 if (target_supports_vfork_events ())
2405 strcat (own_buf
, ";vfork-events+");
2407 if (target_supports_exec_events ())
2408 strcat (own_buf
, ";exec-events+");
2410 if (target_supports_non_stop ())
2411 strcat (own_buf
, ";QNonStop+");
2413 if (target_supports_disable_randomization ())
2414 strcat (own_buf
, ";QDisableRandomization+");
2416 strcat (own_buf
, ";qXfer:threads:read+");
2418 if (target_supports_tracepoints ())
2420 strcat (own_buf
, ";ConditionalTracepoints+");
2421 strcat (own_buf
, ";TraceStateVariables+");
2422 strcat (own_buf
, ";TracepointSource+");
2423 strcat (own_buf
, ";DisconnectedTracing+");
2424 if (gdb_supports_qRelocInsn
&& target_supports_fast_tracepoints ())
2425 strcat (own_buf
, ";FastTracepoints+");
2426 strcat (own_buf
, ";StaticTracepoints+");
2427 strcat (own_buf
, ";InstallInTrace+");
2428 strcat (own_buf
, ";qXfer:statictrace:read+");
2429 strcat (own_buf
, ";qXfer:traceframe-info:read+");
2430 strcat (own_buf
, ";EnableDisableTracepoints+");
2431 strcat (own_buf
, ";QTBuffer:size+");
2432 strcat (own_buf
, ";tracenz+");
2435 if (target_supports_hardware_single_step ()
2436 || target_supports_software_single_step () )
2438 strcat (own_buf
, ";ConditionalBreakpoints+");
2440 strcat (own_buf
, ";BreakpointCommands+");
2442 if (target_supports_agent ())
2443 strcat (own_buf
, ";QAgent+");
2445 supported_btrace_packets (own_buf
);
2447 if (target_supports_stopped_by_sw_breakpoint ())
2448 strcat (own_buf
, ";swbreak+");
2450 if (target_supports_stopped_by_hw_breakpoint ())
2451 strcat (own_buf
, ";hwbreak+");
2453 if (the_target
->pid_to_exec_file
!= NULL
)
2454 strcat (own_buf
, ";qXfer:exec-file:read+");
2456 strcat (own_buf
, ";vContSupported+");
2458 strcat (own_buf
, ";QThreadEvents+");
2460 strcat (own_buf
, ";no-resumed+");
2462 /* Reinitialize components as needed for the new connection. */
2463 hostio_handle_new_gdb_connection ();
2464 target_handle_new_gdb_connection ();
2469 /* Thread-local storage support. */
2470 if (the_target
->pt
->supports_get_tls_address ()
2471 && startswith (own_buf
, "qGetTLSAddr:"))
2473 char *p
= own_buf
+ 12;
2474 CORE_ADDR parts
[2], address
= 0;
2476 ptid_t ptid
= null_ptid
;
2478 require_running_or_return (own_buf
);
2480 for (i
= 0; i
< 3; i
++)
2488 p2
= strchr (p
, ',');
2501 ptid
= read_ptid (p
, NULL
);
2503 decode_address (&parts
[i
- 1], p
, len
);
2507 if (p
!= NULL
|| i
< 3)
2511 struct thread_info
*thread
= find_thread_ptid (ptid
);
2516 err
= the_target
->pt
->get_tls_address (thread
, parts
[0], parts
[1],
2522 strcpy (own_buf
, paddress(address
));
2527 write_enn (own_buf
);
2531 /* Otherwise, pretend we do not understand this packet. */
2534 /* Windows OS Thread Information Block address support. */
2535 if (the_target
->pt
->supports_get_tib_address ()
2536 && startswith (own_buf
, "qGetTIBAddr:"))
2541 ptid_t ptid
= read_ptid (own_buf
+ 12, &annex
);
2543 n
= the_target
->pt
->get_tib_address (ptid
, &tlb
);
2546 strcpy (own_buf
, paddress(tlb
));
2551 write_enn (own_buf
);
2557 /* Handle "monitor" commands. */
2558 if (startswith (own_buf
, "qRcmd,"))
2560 char *mon
= (char *) malloc (PBUFSIZ
);
2561 int len
= strlen (own_buf
+ 6);
2565 write_enn (own_buf
);
2570 || hex2bin (own_buf
+ 6, (gdb_byte
*) mon
, len
/ 2) != len
/ 2)
2572 write_enn (own_buf
);
2576 mon
[len
/ 2] = '\0';
2580 if (the_target
->pt
->handle_monitor_command (mon
) == 0)
2581 /* Default processing. */
2582 handle_monitor_command (mon
, own_buf
);
2588 if (startswith (own_buf
, "qSearch:memory:"))
2590 require_running_or_return (own_buf
);
2591 handle_search_memory (own_buf
, packet_len
);
2595 if (strcmp (own_buf
, "qAttached") == 0
2596 || startswith (own_buf
, "qAttached:"))
2598 struct process_info
*process
;
2600 if (own_buf
[sizeof ("qAttached") - 1])
2602 int pid
= strtoul (own_buf
+ sizeof ("qAttached:") - 1, NULL
, 16);
2603 process
= find_process_pid (pid
);
2607 require_running_or_return (own_buf
);
2608 process
= current_process ();
2611 if (process
== NULL
)
2613 write_enn (own_buf
);
2617 strcpy (own_buf
, process
->attached
? "1" : "0");
2621 if (startswith (own_buf
, "qCRC:"))
2623 /* CRC check (compare-section). */
2627 unsigned long long crc
;
2629 require_running_or_return (own_buf
);
2630 comma
= unpack_varlen_hex (own_buf
+ 5, &base
);
2631 if (*comma
++ != ',')
2633 write_enn (own_buf
);
2636 len
= strtoul (comma
, NULL
, 16);
2637 crc
= crc32 (base
, len
, 0xffffffff);
2638 /* Check for memory failure. */
2639 if (crc
== (unsigned long long) -1)
2641 write_enn (own_buf
);
2644 sprintf (own_buf
, "C%lx", (unsigned long) crc
);
2648 if (handle_qxfer (own_buf
, packet_len
, new_packet_len_p
))
2651 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf
))
2654 /* Otherwise we didn't know what packet it was. Say we didn't
2659 static void gdb_wants_all_threads_stopped (void);
2660 static void resume (struct thread_resume
*actions
, size_t n
);
2662 /* The callback that is passed to visit_actioned_threads. */
2663 typedef int (visit_actioned_threads_callback_ftype
)
2664 (const struct thread_resume
*, struct thread_info
*);
2666 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
2667 true if CALLBACK returns true. Returns false if no matching thread
2668 is found or CALLBACK results false.
2669 Note: This function is itself a callback for find_thread. */
2672 visit_actioned_threads (thread_info
*thread
,
2673 const struct thread_resume
*actions
,
2675 visit_actioned_threads_callback_ftype
*callback
)
2677 for (size_t i
= 0; i
< num_actions
; i
++)
2679 const struct thread_resume
*action
= &actions
[i
];
2681 if (action
->thread
== minus_one_ptid
2682 || action
->thread
== thread
->id
2683 || ((action
->thread
.pid ()
2684 == thread
->id
.pid ())
2685 && action
->thread
.lwp () == -1))
2687 if ((*callback
) (action
, thread
))
2695 /* Callback for visit_actioned_threads. If the thread has a pending
2696 status to report, report it now. */
2699 handle_pending_status (const struct thread_resume
*resumption
,
2700 struct thread_info
*thread
)
2702 client_state
&cs
= get_client_state ();
2703 if (thread
->status_pending_p
)
2705 thread
->status_pending_p
= 0;
2707 cs
.last_status
= thread
->last_status
;
2708 cs
.last_ptid
= thread
->id
;
2709 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, &cs
.last_status
);
2715 /* Parse vCont packets. */
2717 handle_v_cont (char *own_buf
)
2721 struct thread_resume
*resume_info
;
2722 struct thread_resume default_action
{ null_ptid
};
2724 /* Count the number of semicolons in the packet. There should be one
2725 for every action. */
2731 p
= strchr (p
, ';');
2734 resume_info
= (struct thread_resume
*) malloc (n
* sizeof (resume_info
[0]));
2735 if (resume_info
== NULL
)
2743 memset (&resume_info
[i
], 0, sizeof resume_info
[i
]);
2745 if (p
[0] == 's' || p
[0] == 'S')
2746 resume_info
[i
].kind
= resume_step
;
2747 else if (p
[0] == 'r')
2748 resume_info
[i
].kind
= resume_step
;
2749 else if (p
[0] == 'c' || p
[0] == 'C')
2750 resume_info
[i
].kind
= resume_continue
;
2751 else if (p
[0] == 't')
2752 resume_info
[i
].kind
= resume_stop
;
2756 if (p
[0] == 'S' || p
[0] == 'C')
2759 int sig
= strtol (p
+ 1, &q
, 16);
2764 if (!gdb_signal_to_host_p ((enum gdb_signal
) sig
))
2766 resume_info
[i
].sig
= gdb_signal_to_host ((enum gdb_signal
) sig
);
2768 else if (p
[0] == 'r')
2772 p
= unpack_varlen_hex (p
+ 1, &addr
);
2773 resume_info
[i
].step_range_start
= addr
;
2778 p
= unpack_varlen_hex (p
+ 1, &addr
);
2779 resume_info
[i
].step_range_end
= addr
;
2788 resume_info
[i
].thread
= minus_one_ptid
;
2789 default_action
= resume_info
[i
];
2791 /* Note: we don't increment i here, we'll overwrite this entry
2792 the next time through. */
2794 else if (p
[0] == ':')
2797 ptid_t ptid
= read_ptid (p
+ 1, &q
);
2802 if (p
[0] != ';' && p
[0] != 0)
2805 resume_info
[i
].thread
= ptid
;
2812 resume_info
[i
] = default_action
;
2814 resume (resume_info
, n
);
2819 write_enn (own_buf
);
2824 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
2827 resume (struct thread_resume
*actions
, size_t num_actions
)
2829 client_state
&cs
= get_client_state ();
2832 /* Check if among the threads that GDB wants actioned, there's
2833 one with a pending status to report. If so, skip actually
2834 resuming/stopping and report the pending event
2837 thread_info
*thread_with_status
= find_thread ([&] (thread_info
*thread
)
2839 return visit_actioned_threads (thread
, actions
, num_actions
,
2840 handle_pending_status
);
2843 if (thread_with_status
!= NULL
)
2849 the_target
->pt
->resume (actions
, num_actions
);
2852 write_ok (cs
.own_buf
);
2855 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
, 0, 1);
2857 if (cs
.last_status
.kind
== TARGET_WAITKIND_NO_RESUMED
2858 && !report_no_resumed
)
2860 /* The client does not support this stop reply. At least
2862 sprintf (cs
.own_buf
, "E.No unwaited-for children left.");
2863 disable_async_io ();
2867 if (cs
.last_status
.kind
!= TARGET_WAITKIND_EXITED
2868 && cs
.last_status
.kind
!= TARGET_WAITKIND_SIGNALLED
2869 && cs
.last_status
.kind
!= TARGET_WAITKIND_NO_RESUMED
)
2870 current_thread
->last_status
= cs
.last_status
;
2872 /* From the client's perspective, all-stop mode always stops all
2873 threads implicitly (and the target backend has already done
2874 so by now). Tag all threads as "want-stopped", so we don't
2875 resume them implicitly without the client telling us to. */
2876 gdb_wants_all_threads_stopped ();
2877 prepare_resume_reply (cs
.own_buf
, cs
.last_ptid
, &cs
.last_status
);
2878 disable_async_io ();
2880 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
2881 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
2882 target_mourn_inferior (cs
.last_ptid
);
2886 /* Attach to a new program. Return 1 if successful, 0 if failure. */
2888 handle_v_attach (char *own_buf
)
2890 client_state
&cs
= get_client_state ();
2893 pid
= strtol (own_buf
+ 8, NULL
, 16);
2894 if (pid
!= 0 && attach_inferior (pid
) == 0)
2896 /* Don't report shared library events after attaching, even if
2897 some libraries are preloaded. GDB will always poll the
2898 library list. Avoids the "stopped by shared library event"
2899 notice on the GDB side. */
2904 /* In non-stop, we don't send a resume reply. Stop events
2905 will follow up using the normal notification
2910 prepare_resume_reply (own_buf
, cs
.last_ptid
, &cs
.last_status
);
2916 write_enn (own_buf
);
2921 /* Run a new program. Return 1 if successful, 0 if failure. */
2923 handle_v_run (char *own_buf
)
2925 client_state
&cs
= get_client_state ();
2927 std::vector
<char *> new_argv
;
2928 char *new_program_name
= NULL
;
2932 for (p
= own_buf
+ strlen ("vRun;"); p
&& *p
; p
= strchr (p
, ';'))
2938 for (i
= 0, p
= own_buf
+ strlen ("vRun;"); *p
; p
= next_p
, ++i
)
2940 next_p
= strchr (p
, ';');
2942 next_p
= p
+ strlen (p
);
2944 if (i
== 0 && p
== next_p
)
2946 /* No program specified. */
2947 new_program_name
= NULL
;
2949 else if (p
== next_p
)
2951 /* Empty argument. */
2952 new_argv
.push_back (xstrdup ("''"));
2956 size_t len
= (next_p
- p
) / 2;
2957 /* ARG is the unquoted argument received via the RSP. */
2958 char *arg
= (char *) xmalloc (len
+ 1);
2959 /* FULL_ARGS will contain the quoted version of ARG. */
2960 char *full_arg
= (char *) xmalloc ((len
+ 1) * 2);
2961 /* These are pointers used to navigate the strings above. */
2962 char *tmp_arg
= arg
;
2963 char *tmp_full_arg
= full_arg
;
2966 hex2bin (p
, (gdb_byte
*) arg
, len
);
2969 while (*tmp_arg
!= '\0')
2975 *tmp_full_arg
= '\'';
2981 /* Quote single quote. */
2982 *tmp_full_arg
= '\\';
2990 *tmp_full_arg
= *tmp_arg
;
2996 *tmp_full_arg
++ = '\'';
2998 /* Finish FULL_ARG and push it into the vector containing
3000 *tmp_full_arg
= '\0';
3002 new_program_name
= full_arg
;
3004 new_argv
.push_back (full_arg
);
3010 new_argv
.push_back (NULL
);
3012 if (new_program_name
== NULL
)
3014 /* GDB didn't specify a program to run. Use the program from the
3015 last run with the new argument list. */
3016 if (program_path
.get () == NULL
)
3018 write_enn (own_buf
);
3019 free_vector_argv (new_argv
);
3024 program_path
.set (gdb::unique_xmalloc_ptr
<char> (new_program_name
));
3026 /* Free the old argv and install the new one. */
3027 free_vector_argv (program_args
);
3028 program_args
= new_argv
;
3030 target_create_inferior (program_path
.get (), program_args
);
3032 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
3034 prepare_resume_reply (own_buf
, cs
.last_ptid
, &cs
.last_status
);
3036 /* In non-stop, sending a resume reply doesn't set the general
3037 thread, but GDB assumes a vRun sets it (this is so GDB can
3038 query which is the main thread of the new inferior. */
3040 cs
.general_thread
= cs
.last_ptid
;
3046 write_enn (own_buf
);
3051 /* Kill process. Return 1 if successful, 0 if failure. */
3053 handle_v_kill (char *own_buf
)
3055 client_state
&cs
= get_client_state ();
3057 char *p
= &own_buf
[6];
3058 if (cs
.multi_process
)
3059 pid
= strtol (p
, NULL
, 16);
3063 process_info
*proc
= find_process_pid (pid
);
3065 if (proc
!= nullptr && kill_inferior (proc
) == 0)
3067 cs
.last_status
.kind
= TARGET_WAITKIND_SIGNALLED
;
3068 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
3069 cs
.last_ptid
= ptid_t (pid
);
3070 discard_queued_stop_replies (cs
.last_ptid
);
3076 write_enn (own_buf
);
3081 /* Handle all of the extended 'v' packets. */
3083 handle_v_requests (char *own_buf
, int packet_len
, int *new_packet_len
)
3085 client_state
&cs
= get_client_state ();
3086 if (!disable_packet_vCont
)
3088 if (strcmp (own_buf
, "vCtrlC") == 0)
3090 the_target
->pt
->request_interrupt ();
3095 if (startswith (own_buf
, "vCont;"))
3097 handle_v_cont (own_buf
);
3101 if (startswith (own_buf
, "vCont?"))
3103 strcpy (own_buf
, "vCont;c;C;t");
3105 if (target_supports_hardware_single_step ()
3106 || target_supports_software_single_step ()
3107 || !cs
.vCont_supported
)
3109 /* If target supports single step either by hardware or by
3110 software, add actions s and S to the list of supported
3111 actions. On the other hand, if GDB doesn't request the
3112 supported vCont actions in qSupported packet, add s and
3113 S to the list too. */
3114 own_buf
= own_buf
+ strlen (own_buf
);
3115 strcpy (own_buf
, ";s;S");
3118 if (target_supports_range_stepping ())
3120 own_buf
= own_buf
+ strlen (own_buf
);
3121 strcpy (own_buf
, ";r");
3127 if (startswith (own_buf
, "vFile:")
3128 && handle_vFile (own_buf
, packet_len
, new_packet_len
))
3131 if (startswith (own_buf
, "vAttach;"))
3133 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3135 fprintf (stderr
, "Already debugging a process\n");
3136 write_enn (own_buf
);
3139 handle_v_attach (own_buf
);
3143 if (startswith (own_buf
, "vRun;"))
3145 if ((!extended_protocol
|| !cs
.multi_process
) && target_running ())
3147 fprintf (stderr
, "Already debugging a process\n");
3148 write_enn (own_buf
);
3151 handle_v_run (own_buf
);
3155 if (startswith (own_buf
, "vKill;"))
3157 if (!target_running ())
3159 fprintf (stderr
, "No process to kill\n");
3160 write_enn (own_buf
);
3163 handle_v_kill (own_buf
);
3167 if (handle_notif_ack (own_buf
, packet_len
))
3170 /* Otherwise we didn't know what packet it was. Say we didn't
3176 /* Resume thread and wait for another event. In non-stop mode,
3177 don't really wait here, but return immediatelly to the event
3180 myresume (char *own_buf
, int step
, int sig
)
3182 client_state
&cs
= get_client_state ();
3183 struct thread_resume resume_info
[2];
3185 int valid_cont_thread
;
3187 valid_cont_thread
= (cs
.cont_thread
!= null_ptid
3188 && cs
.cont_thread
!= minus_one_ptid
);
3190 if (step
|| sig
|| valid_cont_thread
)
3192 resume_info
[0].thread
= current_ptid
;
3194 resume_info
[0].kind
= resume_step
;
3196 resume_info
[0].kind
= resume_continue
;
3197 resume_info
[0].sig
= sig
;
3201 if (!valid_cont_thread
)
3203 resume_info
[n
].thread
= minus_one_ptid
;
3204 resume_info
[n
].kind
= resume_continue
;
3205 resume_info
[n
].sig
= 0;
3209 resume (resume_info
, n
);
3212 /* Callback for for_each_thread. Make a new stop reply for each
3216 queue_stop_reply_callback (thread_info
*thread
)
3218 /* For now, assume targets that don't have this callback also don't
3219 manage the thread's last_status field. */
3220 if (!the_target
->pt
->supports_thread_stopped ())
3222 struct vstop_notif
*new_notif
= new struct vstop_notif
;
3224 new_notif
->ptid
= thread
->id
;
3225 new_notif
->status
= thread
->last_status
;
3226 /* Pass the last stop reply back to GDB, but don't notify
3228 notif_event_enque (¬if_stop
, new_notif
);
3232 if (target_thread_stopped (thread
))
3236 std::string status_string
3237 = target_waitstatus_to_string (&thread
->last_status
);
3239 debug_printf ("Reporting thread %s as already stopped with %s\n",
3240 target_pid_to_str (thread
->id
),
3241 status_string
.c_str ());
3244 gdb_assert (thread
->last_status
.kind
!= TARGET_WAITKIND_IGNORE
);
3246 /* Pass the last stop reply back to GDB, but don't notify
3248 queue_stop_reply (thread
->id
, &thread
->last_status
);
3253 /* Set this inferior threads's state as "want-stopped". We won't
3254 resume this thread until the client gives us another action for
3258 gdb_wants_thread_stopped (thread_info
*thread
)
3260 thread
->last_resume_kind
= resume_stop
;
3262 if (thread
->last_status
.kind
== TARGET_WAITKIND_IGNORE
)
3264 /* Most threads are stopped implicitly (all-stop); tag that with
3266 thread
->last_status
.kind
= TARGET_WAITKIND_STOPPED
;
3267 thread
->last_status
.value
.sig
= GDB_SIGNAL_0
;
3271 /* Set all threads' states as "want-stopped". */
3274 gdb_wants_all_threads_stopped (void)
3276 for_each_thread (gdb_wants_thread_stopped
);
3279 /* Callback for for_each_thread. If the thread is stopped with an
3280 interesting event, mark it as having a pending event. */
3283 set_pending_status_callback (thread_info
*thread
)
3285 if (thread
->last_status
.kind
!= TARGET_WAITKIND_STOPPED
3286 || (thread
->last_status
.value
.sig
!= GDB_SIGNAL_0
3287 /* A breakpoint, watchpoint or finished step from a previous
3288 GDB run isn't considered interesting for a new GDB run.
3289 If we left those pending, the new GDB could consider them
3290 random SIGTRAPs. This leaves out real async traps. We'd
3291 have to peek into the (target-specific) siginfo to
3292 distinguish those. */
3293 && thread
->last_status
.value
.sig
!= GDB_SIGNAL_TRAP
))
3294 thread
->status_pending_p
= 1;
3297 /* Status handler for the '?' packet. */
3300 handle_status (char *own_buf
)
3302 client_state
&cs
= get_client_state ();
3304 /* GDB is connected, don't forward events to the target anymore. */
3305 for_each_process ([] (process_info
*process
) {
3306 process
->gdb_detached
= 0;
3309 /* In non-stop mode, we must send a stop reply for each stopped
3310 thread. In all-stop mode, just send one for the first stopped
3315 for_each_thread (queue_stop_reply_callback
);
3317 /* The first is sent immediatly. OK is sent if there is no
3318 stopped thread, which is the same handling of the vStopped
3319 packet (by design). */
3320 notif_write_event (¬if_stop
, cs
.own_buf
);
3324 thread_info
*thread
= NULL
;
3326 target_pause_all (false);
3327 stabilize_threads ();
3328 gdb_wants_all_threads_stopped ();
3330 /* We can only report one status, but we might be coming out of
3331 non-stop -- if more than one thread is stopped with
3332 interesting events, leave events for the threads we're not
3333 reporting now pending. They'll be reported the next time the
3334 threads are resumed. Start by marking all interesting events
3336 for_each_thread (set_pending_status_callback
);
3338 /* Prefer the last thread that reported an event to GDB (even if
3339 that was a GDB_SIGNAL_TRAP). */
3340 if (cs
.last_status
.kind
!= TARGET_WAITKIND_IGNORE
3341 && cs
.last_status
.kind
!= TARGET_WAITKIND_EXITED
3342 && cs
.last_status
.kind
!= TARGET_WAITKIND_SIGNALLED
)
3343 thread
= find_thread_ptid (cs
.last_ptid
);
3345 /* If the last event thread is not found for some reason, look
3346 for some other thread that might have an event to report. */
3348 thread
= find_thread ([] (thread_info
*thr_arg
)
3350 return thr_arg
->status_pending_p
;
3353 /* If we're still out of luck, simply pick the first thread in
3356 thread
= get_first_thread ();
3360 struct thread_info
*tp
= (struct thread_info
*) thread
;
3362 /* We're reporting this event, so it's no longer
3364 tp
->status_pending_p
= 0;
3366 /* GDB assumes the current thread is the thread we're
3367 reporting the status for. */
3368 cs
.general_thread
= thread
->id
;
3369 set_desired_thread ();
3371 gdb_assert (tp
->last_status
.kind
!= TARGET_WAITKIND_IGNORE
);
3372 prepare_resume_reply (own_buf
, tp
->id
, &tp
->last_status
);
3375 strcpy (own_buf
, "W00");
3380 gdbserver_version (void)
3382 printf ("GNU gdbserver %s%s\n"
3383 "Copyright (C) 2020 Free Software Foundation, Inc.\n"
3384 "gdbserver is free software, covered by the "
3385 "GNU General Public License.\n"
3386 "This gdbserver was configured as \"%s\"\n",
3387 PKGVERSION
, version
, host_name
);
3391 gdbserver_usage (FILE *stream
)
3393 fprintf (stream
, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3394 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3395 "\tgdbserver [OPTIONS] --multi COMM\n"
3397 "COMM may either be a tty device (for serial debugging),\n"
3398 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3399 "stdin/stdout of gdbserver.\n"
3400 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3401 "PID is the process ID to attach to, when --attach is specified.\n"
3403 "Operating modes:\n"
3405 " --attach Attach to running process PID.\n"
3406 " --multi Start server without a specific program, and\n"
3407 " only quit when explicitly commanded.\n"
3408 " --once Exit after the first connection has closed.\n"
3409 " --help Print this message and then exit.\n"
3410 " --version Display version information and exit.\n"
3414 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3415 " --disable-randomization\n"
3416 " Run PROG with address space randomization disabled.\n"
3417 " --no-disable-randomization\n"
3418 " Don't disable address space randomization when\n"
3420 " --startup-with-shell\n"
3421 " Start PROG using a shell. I.e., execs a shell that\n"
3422 " then execs PROG. (default)\n"
3423 " --no-startup-with-shell\n"
3424 " Exec PROG directly instead of using a shell.\n"
3425 " Disables argument globbing and variable substitution\n"
3426 " on UNIX-like systems.\n"
3430 " --debug Enable general debugging output.\n"
3431 " --debug-format=OPT1[,OPT2,...]\n"
3432 " Specify extra content in debugging output.\n"
3437 " --remote-debug Enable remote protocol debugging output.\n"
3438 " --disable-packet=OPT1[,OPT2,...]\n"
3439 " Disable support for RSP packets or features.\n"
3441 " vCont, Tthread, qC, qfThreadInfo and \n"
3442 " threads (disable all threading packets).\n"
3444 "For more information, consult the GDB manual (available as on-line \n"
3445 "info or a printed manual).\n");
3446 if (REPORT_BUGS_TO
[0] && stream
== stdout
)
3447 fprintf (stream
, "Report bugs to \"%s\".\n", REPORT_BUGS_TO
);
3451 gdbserver_show_disableable (FILE *stream
)
3453 fprintf (stream
, "Disableable packets:\n"
3454 " vCont \tAll vCont packets\n"
3455 " qC \tQuerying the current thread\n"
3456 " qfThreadInfo\tThread listing\n"
3457 " Tthread \tPassing the thread specifier in the "
3458 "T stop reply packet\n"
3459 " threads \tAll of the above\n");
3463 kill_inferior_callback (process_info
*process
)
3465 kill_inferior (process
);
3466 discard_queued_stop_replies (ptid_t (process
->pid
));
3469 /* Call this when exiting gdbserver with possible inferiors that need
3470 to be killed or detached from. */
3473 detach_or_kill_for_exit (void)
3475 /* First print a list of the inferiors we will be killing/detaching.
3476 This is to assist the user, for example, in case the inferior unexpectedly
3477 dies after we exit: did we screw up or did the inferior exit on its own?
3478 Having this info will save some head-scratching. */
3480 if (have_started_inferiors_p ())
3482 fprintf (stderr
, "Killing process(es):");
3484 for_each_process ([] (process_info
*process
) {
3485 if (!process
->attached
)
3486 fprintf (stderr
, " %d", process
->pid
);
3489 fprintf (stderr
, "\n");
3491 if (have_attached_inferiors_p ())
3493 fprintf (stderr
, "Detaching process(es):");
3495 for_each_process ([] (process_info
*process
) {
3496 if (process
->attached
)
3497 fprintf (stderr
, " %d", process
->pid
);
3500 fprintf (stderr
, "\n");
3503 /* Now we can kill or detach the inferiors. */
3504 for_each_process ([] (process_info
*process
) {
3505 int pid
= process
->pid
;
3507 if (process
->attached
)
3508 detach_inferior (process
);
3510 kill_inferior (process
);
3512 discard_queued_stop_replies (ptid_t (pid
));
3516 /* Value that will be passed to exit(3) when gdbserver exits. */
3517 static int exit_code
;
3519 /* Wrapper for detach_or_kill_for_exit that catches and prints
3523 detach_or_kill_for_exit_cleanup ()
3527 detach_or_kill_for_exit ();
3529 catch (const gdb_exception
&exception
)
3532 fprintf (stderr
, "Detach or kill failed: %s\n",
3538 /* Main function. This is called by the real "main" function,
3539 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
3541 static void ATTRIBUTE_NORETURN
3542 captured_main (int argc
, char *argv
[])
3547 const char *port
= NULL
;
3548 char **next_arg
= &argv
[1];
3549 volatile int multi_mode
= 0;
3550 volatile int attach
= 0;
3552 bool selftest
= false;
3554 const char *selftest_filter
= NULL
;
3557 current_directory
= getcwd (NULL
, 0);
3558 client_state
&cs
= get_client_state ();
3560 if (current_directory
== NULL
)
3562 error (_("Could not find current working directory: %s"),
3563 safe_strerror (errno
));
3566 while (*next_arg
!= NULL
&& **next_arg
== '-')
3568 if (strcmp (*next_arg
, "--version") == 0)
3570 gdbserver_version ();
3573 else if (strcmp (*next_arg
, "--help") == 0)
3575 gdbserver_usage (stdout
);
3578 else if (strcmp (*next_arg
, "--attach") == 0)
3580 else if (strcmp (*next_arg
, "--multi") == 0)
3582 else if (strcmp (*next_arg
, "--wrapper") == 0)
3589 while (*next_arg
!= NULL
&& strcmp (*next_arg
, "--") != 0)
3591 wrapper_argv
+= *next_arg
;
3592 wrapper_argv
+= ' ';
3596 if (!wrapper_argv
.empty ())
3598 /* Erase the last whitespace. */
3599 wrapper_argv
.erase (wrapper_argv
.end () - 1);
3602 if (next_arg
== tmp
|| *next_arg
== NULL
)
3604 gdbserver_usage (stderr
);
3608 /* Consume the "--". */
3611 else if (strcmp (*next_arg
, "--debug") == 0)
3613 else if (startswith (*next_arg
, "--debug-format="))
3615 std::string error_msg
3616 = parse_debug_format_options ((*next_arg
)
3617 + sizeof ("--debug-format=") - 1, 0);
3619 if (!error_msg
.empty ())
3621 fprintf (stderr
, "%s", error_msg
.c_str ());
3625 else if (strcmp (*next_arg
, "--remote-debug") == 0)
3627 else if (startswith (*next_arg
, "--debug-file="))
3628 debug_set_output ((*next_arg
) + sizeof ("--debug-file=") -1);
3629 else if (strcmp (*next_arg
, "--disable-packet") == 0)
3631 gdbserver_show_disableable (stdout
);
3634 else if (startswith (*next_arg
, "--disable-packet="))
3636 char *packets
= *next_arg
+= sizeof ("--disable-packet=") - 1;
3638 for (char *tok
= strtok_r (packets
, ",", &saveptr
);
3640 tok
= strtok_r (NULL
, ",", &saveptr
))
3642 if (strcmp ("vCont", tok
) == 0)
3643 disable_packet_vCont
= true;
3644 else if (strcmp ("Tthread", tok
) == 0)
3645 disable_packet_Tthread
= true;
3646 else if (strcmp ("qC", tok
) == 0)
3647 disable_packet_qC
= true;
3648 else if (strcmp ("qfThreadInfo", tok
) == 0)
3649 disable_packet_qfThreadInfo
= true;
3650 else if (strcmp ("threads", tok
) == 0)
3652 disable_packet_vCont
= true;
3653 disable_packet_Tthread
= true;
3654 disable_packet_qC
= true;
3655 disable_packet_qfThreadInfo
= true;
3659 fprintf (stderr
, "Don't know how to disable \"%s\".\n\n",
3661 gdbserver_show_disableable (stderr
);
3666 else if (strcmp (*next_arg
, "-") == 0)
3668 /* "-" specifies a stdio connection and is a form of port
3670 port
= STDIO_CONNECTION_NAME
;
3674 else if (strcmp (*next_arg
, "--disable-randomization") == 0)
3675 cs
.disable_randomization
= 1;
3676 else if (strcmp (*next_arg
, "--no-disable-randomization") == 0)
3677 cs
.disable_randomization
= 0;
3678 else if (strcmp (*next_arg
, "--startup-with-shell") == 0)
3679 startup_with_shell
= true;
3680 else if (strcmp (*next_arg
, "--no-startup-with-shell") == 0)
3681 startup_with_shell
= false;
3682 else if (strcmp (*next_arg
, "--once") == 0)
3684 else if (strcmp (*next_arg
, "--selftest") == 0)
3686 else if (startswith (*next_arg
, "--selftest="))
3690 selftest_filter
= *next_arg
+ strlen ("--selftest=");
3695 fprintf (stderr
, "Unknown argument: %s\n", *next_arg
);
3708 if ((port
== NULL
|| (!attach
&& !multi_mode
&& *next_arg
== NULL
))
3711 gdbserver_usage (stderr
);
3715 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
3716 opened by remote_prepare. */
3719 save_original_signals_state (false);
3721 /* We need to know whether the remote connection is stdio before
3722 starting the inferior. Inferiors created in this scenario have
3723 stdin,stdout redirected. So do this here before we call
3726 remote_prepare (port
);
3731 /* --attach used to come after PORT, so allow it there for
3733 if (*next_arg
!= NULL
&& strcmp (*next_arg
, "--attach") == 0)
3740 && (*next_arg
== NULL
3741 || (*next_arg
)[0] == '\0'
3742 || (pid
= strtoul (*next_arg
, &arg_end
, 0)) == 0
3744 || next_arg
[1] != NULL
))
3749 gdbserver_usage (stderr
);
3753 /* Gather information about the environment. */
3754 our_environ
= gdb_environ::from_host_environ ();
3756 initialize_async_io ();
3758 have_job_control ();
3759 initialize_event_loop ();
3760 if (target_supports_tracepoints ())
3761 initialize_tracepoint ();
3763 mem_buf
= (unsigned char *) xmalloc (PBUFSIZ
);
3768 selftests::run_tests (selftest_filter
);
3770 printf (_("Selftests have been disabled for this build.\n"));
3772 throw_quit ("Quit");
3775 if (pid
== 0 && *next_arg
!= NULL
)
3779 n
= argc
- (next_arg
- argv
);
3780 program_path
.set (make_unique_xstrdup (next_arg
[0]));
3781 for (i
= 1; i
< n
; i
++)
3782 program_args
.push_back (xstrdup (next_arg
[i
]));
3783 program_args
.push_back (NULL
);
3785 /* Wait till we are at first instruction in program. */
3786 target_create_inferior (program_path
.get (), program_args
);
3788 /* We are now (hopefully) stopped at the first instruction of
3789 the target process. This assumes that the target process was
3790 successfully created. */
3794 if (attach_inferior (pid
) == -1)
3795 error ("Attaching not supported on this target");
3797 /* Otherwise succeeded. */
3801 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
3802 cs
.last_status
.value
.integer
= 0;
3803 cs
.last_ptid
= minus_one_ptid
;
3806 SCOPE_EXIT
{ detach_or_kill_for_exit_cleanup (); };
3808 /* Don't report shared library events on the initial connection,
3809 even if some libraries are preloaded. Avoids the "stopped by
3810 shared library event" notice on gdb side. */
3813 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
3814 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
3819 if (!was_running
&& !multi_mode
)
3820 error ("No program to debug");
3825 cs
.multi_process
= 0;
3826 cs
.report_fork_events
= 0;
3827 cs
.report_vfork_events
= 0;
3828 cs
.report_exec_events
= 0;
3829 /* Be sure we're out of tfind mode. */
3830 cs
.current_traceframe
= -1;
3831 cs
.cont_thread
= null_ptid
;
3832 cs
.swbreak_feature
= 0;
3833 cs
.hwbreak_feature
= 0;
3834 cs
.vCont_supported
= 0;
3840 /* Wait for events. This will return when all event sources
3841 are removed from the event loop. */
3842 start_event_loop ();
3844 /* If an exit was requested (using the "monitor exit"
3845 command), terminate now. */
3847 throw_quit ("Quit");
3849 /* The only other way to get here is for getpkt to fail:
3851 - If --once was specified, we're done.
3853 - If not in extended-remote mode, and we're no longer
3854 debugging anything, simply exit: GDB has disconnected
3855 after processing the last process exit.
3857 - Otherwise, close the connection and reopen it at the
3859 if (run_once
|| (!extended_protocol
&& !target_running ()))
3860 throw_quit ("Quit");
3863 "Remote side has terminated connection. "
3864 "GDBserver will reopen the connection.\n");
3866 /* Get rid of any pending statuses. An eventual reconnection
3867 (by the same GDB instance or another) will refresh all its
3868 state from scratch. */
3869 discard_queued_stop_replies (minus_one_ptid
);
3870 for_each_thread ([] (thread_info
*thread
)
3872 thread
->status_pending_p
= 0;
3877 if (disconnected_tracing
)
3879 /* Try to enable non-stop/async mode, so we we can
3880 both wait for an async socket accept, and handle
3881 async target events simultaneously. There's also
3882 no point either in having the target always stop
3883 all threads, when we're going to pass signals
3884 down without informing GDB. */
3887 if (the_target
->pt
->start_non_stop (true))
3890 /* Detaching implicitly resumes all threads;
3891 simply disconnecting does not. */
3897 "Disconnected tracing disabled; "
3898 "stopping trace run.\n");
3903 catch (const gdb_exception_error
&exception
)
3906 fprintf (stderr
, "gdbserver: %s\n", exception
.what ());
3908 if (response_needed
)
3910 write_enn (cs
.own_buf
);
3911 putpkt (cs
.own_buf
);
3915 throw_quit ("Quit");
3920 /* Main function. */
3923 main (int argc
, char *argv
[])
3928 captured_main (argc
, argv
);
3930 catch (const gdb_exception
&exception
)
3932 if (exception
.reason
== RETURN_ERROR
)
3935 fprintf (stderr
, "%s\n", exception
.what ());
3936 fprintf (stderr
, "Exiting\n");
3943 gdb_assert_not_reached ("captured_main should never return");
3946 /* Process options coming from Z packets for a breakpoint. PACKET is
3947 the packet buffer. *PACKET is updated to point to the first char
3948 after the last processed option. */
3951 process_point_options (struct gdb_breakpoint
*bp
, const char **packet
)
3953 const char *dataptr
= *packet
;
3956 /* Check if data has the correct format. */
3957 if (*dataptr
!= ';')
3964 if (*dataptr
== ';')
3967 if (*dataptr
== 'X')
3969 /* Conditional expression. */
3971 debug_printf ("Found breakpoint condition.\n");
3972 if (!add_breakpoint_condition (bp
, &dataptr
))
3973 dataptr
= strchrnul (dataptr
, ';');
3975 else if (startswith (dataptr
, "cmds:"))
3977 dataptr
+= strlen ("cmds:");
3979 debug_printf ("Found breakpoint commands %s.\n", dataptr
);
3980 persist
= (*dataptr
== '1');
3982 if (add_breakpoint_commands (bp
, &dataptr
, persist
))
3983 dataptr
= strchrnul (dataptr
, ';');
3987 fprintf (stderr
, "Unknown token %c, ignoring.\n",
3989 /* Skip tokens until we find one that we recognize. */
3990 dataptr
= strchrnul (dataptr
, ';');
3996 /* Event loop callback that handles a serial event. The first byte in
3997 the serial buffer gets us here. We expect characters to arrive at
3998 a brisk pace, so we read the rest of the packet with a blocking
4002 process_serial_event (void)
4004 client_state
&cs
= get_client_state ();
4010 int new_packet_len
= -1;
4012 disable_async_io ();
4014 response_needed
= false;
4015 packet_len
= getpkt (cs
.own_buf
);
4016 if (packet_len
<= 0)
4019 /* Force an event loop break. */
4022 response_needed
= true;
4024 char ch
= cs
.own_buf
[0];
4028 handle_query (cs
.own_buf
, packet_len
, &new_packet_len
);
4031 handle_general_set (cs
.own_buf
);
4034 handle_detach (cs
.own_buf
);
4037 extended_protocol
= true;
4038 write_ok (cs
.own_buf
);
4041 handle_status (cs
.own_buf
);
4044 if (cs
.own_buf
[1] == 'c' || cs
.own_buf
[1] == 'g' || cs
.own_buf
[1] == 's')
4046 require_running_or_break (cs
.own_buf
);
4048 ptid_t thread_id
= read_ptid (&cs
.own_buf
[2], NULL
);
4050 if (thread_id
== null_ptid
|| thread_id
== minus_one_ptid
)
4051 thread_id
= null_ptid
;
4052 else if (thread_id
.is_pid ())
4054 /* The ptid represents a pid. */
4055 thread_info
*thread
= find_any_thread_of_pid (thread_id
.pid ());
4059 write_enn (cs
.own_buf
);
4063 thread_id
= thread
->id
;
4067 /* The ptid represents a lwp/tid. */
4068 if (find_thread_ptid (thread_id
) == NULL
)
4070 write_enn (cs
.own_buf
);
4075 if (cs
.own_buf
[1] == 'g')
4077 if (thread_id
== null_ptid
)
4079 /* GDB is telling us to choose any thread. Check if
4080 the currently selected thread is still valid. If
4081 it is not, select the first available. */
4082 thread_info
*thread
= find_thread_ptid (cs
.general_thread
);
4084 thread
= get_first_thread ();
4085 thread_id
= thread
->id
;
4088 cs
.general_thread
= thread_id
;
4089 set_desired_thread ();
4090 gdb_assert (current_thread
!= NULL
);
4092 else if (cs
.own_buf
[1] == 'c')
4093 cs
.cont_thread
= thread_id
;
4095 write_ok (cs
.own_buf
);
4099 /* Silently ignore it so that gdb can extend the protocol
4100 without compatibility headaches. */
4101 cs
.own_buf
[0] = '\0';
4105 require_running_or_break (cs
.own_buf
);
4106 if (cs
.current_traceframe
>= 0)
4108 struct regcache
*regcache
4109 = new_register_cache (current_target_desc ());
4111 if (fetch_traceframe_registers (cs
.current_traceframe
,
4113 registers_to_string (regcache
, cs
.own_buf
);
4115 write_enn (cs
.own_buf
);
4116 free_register_cache (regcache
);
4120 struct regcache
*regcache
;
4122 if (!set_desired_thread ())
4123 write_enn (cs
.own_buf
);
4126 regcache
= get_thread_regcache (current_thread
, 1);
4127 registers_to_string (regcache
, cs
.own_buf
);
4132 require_running_or_break (cs
.own_buf
);
4133 if (cs
.current_traceframe
>= 0)
4134 write_enn (cs
.own_buf
);
4137 struct regcache
*regcache
;
4139 if (!set_desired_thread ())
4140 write_enn (cs
.own_buf
);
4143 regcache
= get_thread_regcache (current_thread
, 1);
4144 registers_from_string (regcache
, &cs
.own_buf
[1]);
4145 write_ok (cs
.own_buf
);
4151 require_running_or_break (cs
.own_buf
);
4152 decode_m_packet (&cs
.own_buf
[1], &mem_addr
, &len
);
4153 int res
= gdb_read_memory (mem_addr
, mem_buf
, len
);
4155 write_enn (cs
.own_buf
);
4157 bin2hex (mem_buf
, cs
.own_buf
, res
);
4161 require_running_or_break (cs
.own_buf
);
4162 decode_M_packet (&cs
.own_buf
[1], &mem_addr
, &len
, &mem_buf
);
4163 if (gdb_write_memory (mem_addr
, mem_buf
, len
) == 0)
4164 write_ok (cs
.own_buf
);
4166 write_enn (cs
.own_buf
);
4169 require_running_or_break (cs
.own_buf
);
4170 if (decode_X_packet (&cs
.own_buf
[1], packet_len
- 1,
4171 &mem_addr
, &len
, &mem_buf
) < 0
4172 || gdb_write_memory (mem_addr
, mem_buf
, len
) != 0)
4173 write_enn (cs
.own_buf
);
4175 write_ok (cs
.own_buf
);
4178 require_running_or_break (cs
.own_buf
);
4179 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4180 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4181 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4184 myresume (cs
.own_buf
, 0, signal
);
4187 require_running_or_break (cs
.own_buf
);
4188 hex2bin (cs
.own_buf
+ 1, &sig
, 1);
4189 if (gdb_signal_to_host_p ((enum gdb_signal
) sig
))
4190 signal
= gdb_signal_to_host ((enum gdb_signal
) sig
);
4193 myresume (cs
.own_buf
, 1, signal
);
4196 require_running_or_break (cs
.own_buf
);
4198 myresume (cs
.own_buf
, 0, signal
);
4201 require_running_or_break (cs
.own_buf
);
4203 myresume (cs
.own_buf
, 1, signal
);
4205 case 'Z': /* insert_ ... */
4207 case 'z': /* remove_ ... */
4212 char type
= cs
.own_buf
[1];
4214 const int insert
= ch
== 'Z';
4215 const char *p
= &cs
.own_buf
[3];
4217 p
= unpack_varlen_hex (p
, &addr
);
4218 kind
= strtol (p
+ 1, &dataptr
, 16);
4222 struct gdb_breakpoint
*bp
;
4224 bp
= set_gdb_breakpoint (type
, addr
, kind
, &res
);
4229 /* GDB may have sent us a list of *point parameters to
4230 be evaluated on the target's side. Read such list
4231 here. If we already have a list of parameters, GDB
4232 is telling us to drop that list and use this one
4234 clear_breakpoint_conditions_and_commands (bp
);
4235 const char *options
= dataptr
;
4236 process_point_options (bp
, &options
);
4240 res
= delete_gdb_breakpoint (type
, addr
, kind
);
4243 write_ok (cs
.own_buf
);
4246 cs
.own_buf
[0] = '\0';
4248 write_enn (cs
.own_buf
);
4252 response_needed
= false;
4253 if (!target_running ())
4254 /* The packet we received doesn't make sense - but we can't
4255 reply to it, either. */
4258 fprintf (stderr
, "Killing all inferiors\n");
4260 for_each_process (kill_inferior_callback
);
4262 /* When using the extended protocol, we wait with no program
4263 running. The traditional protocol will exit instead. */
4264 if (extended_protocol
)
4266 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
4267 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
4275 require_running_or_break (cs
.own_buf
);
4277 ptid_t thread_id
= read_ptid (&cs
.own_buf
[1], NULL
);
4278 if (find_thread_ptid (thread_id
) == NULL
)
4280 write_enn (cs
.own_buf
);
4284 if (mythread_alive (thread_id
))
4285 write_ok (cs
.own_buf
);
4287 write_enn (cs
.own_buf
);
4291 response_needed
= false;
4293 /* Restarting the inferior is only supported in the extended
4295 if (extended_protocol
)
4297 if (target_running ())
4298 for_each_process (kill_inferior_callback
);
4300 fprintf (stderr
, "GDBserver restarting\n");
4302 /* Wait till we are at 1st instruction in prog. */
4303 if (program_path
.get () != NULL
)
4305 target_create_inferior (program_path
.get (), program_args
);
4307 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
4309 /* Stopped at the first instruction of the target
4311 cs
.general_thread
= cs
.last_ptid
;
4315 /* Something went wrong. */
4316 cs
.general_thread
= null_ptid
;
4321 cs
.last_status
.kind
= TARGET_WAITKIND_EXITED
;
4322 cs
.last_status
.value
.sig
= GDB_SIGNAL_KILL
;
4328 /* It is a request we don't understand. Respond with an
4329 empty packet so that gdb knows that we don't support this
4331 cs
.own_buf
[0] = '\0';
4335 /* Extended (long) request. */
4336 handle_v_requests (cs
.own_buf
, packet_len
, &new_packet_len
);
4340 /* It is a request we don't understand. Respond with an empty
4341 packet so that gdb knows that we don't support this
4343 cs
.own_buf
[0] = '\0';
4347 if (new_packet_len
!= -1)
4348 putpkt_binary (cs
.own_buf
, new_packet_len
);
4350 putpkt (cs
.own_buf
);
4352 response_needed
= false;
4360 /* Event-loop callback for serial events. */
4363 handle_serial_event (int err
, gdb_client_data client_data
)
4366 debug_printf ("handling possible serial event\n");
4368 /* Really handle it. */
4369 if (process_serial_event () < 0)
4372 /* Be sure to not change the selected thread behind GDB's back.
4373 Important in the non-stop mode asynchronous protocol. */
4374 set_desired_thread ();
4379 /* Push a stop notification on the notification queue. */
4382 push_stop_notification (ptid_t ptid
, struct target_waitstatus
*status
)
4384 struct vstop_notif
*vstop_notif
= new struct vstop_notif
;
4386 vstop_notif
->status
= *status
;
4387 vstop_notif
->ptid
= ptid
;
4388 /* Push Stop notification. */
4389 notif_push (¬if_stop
, vstop_notif
);
4392 /* Event-loop callback for target events. */
4395 handle_target_event (int err
, gdb_client_data client_data
)
4397 client_state
&cs
= get_client_state ();
4399 debug_printf ("handling possible target event\n");
4401 cs
.last_ptid
= mywait (minus_one_ptid
, &cs
.last_status
,
4404 if (cs
.last_status
.kind
== TARGET_WAITKIND_NO_RESUMED
)
4406 if (gdb_connected () && report_no_resumed
)
4407 push_stop_notification (null_ptid
, &cs
.last_status
);
4409 else if (cs
.last_status
.kind
!= TARGET_WAITKIND_IGNORE
)
4411 int pid
= cs
.last_ptid
.pid ();
4412 struct process_info
*process
= find_process_pid (pid
);
4413 int forward_event
= !gdb_connected () || process
->gdb_detached
;
4415 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
4416 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
)
4418 mark_breakpoints_out (process
);
4419 target_mourn_inferior (cs
.last_ptid
);
4421 else if (cs
.last_status
.kind
== TARGET_WAITKIND_THREAD_EXITED
)
4425 /* We're reporting this thread as stopped. Update its
4426 "want-stopped" state to what the client wants, until it
4427 gets a new resume action. */
4428 current_thread
->last_resume_kind
= resume_stop
;
4429 current_thread
->last_status
= cs
.last_status
;
4434 if (!target_running ())
4436 /* The last process exited. We're done. */
4440 if (cs
.last_status
.kind
== TARGET_WAITKIND_EXITED
4441 || cs
.last_status
.kind
== TARGET_WAITKIND_SIGNALLED
4442 || cs
.last_status
.kind
== TARGET_WAITKIND_THREAD_EXITED
)
4446 /* A thread stopped with a signal, but gdb isn't
4447 connected to handle it. Pass it down to the
4448 inferior, as if it wasn't being traced. */
4449 enum gdb_signal signal
;
4452 debug_printf ("GDB not connected; forwarding event %d for"
4454 (int) cs
.last_status
.kind
,
4455 target_pid_to_str (cs
.last_ptid
));
4457 if (cs
.last_status
.kind
== TARGET_WAITKIND_STOPPED
)
4458 signal
= cs
.last_status
.value
.sig
;
4460 signal
= GDB_SIGNAL_0
;
4461 target_continue (cs
.last_ptid
, signal
);
4465 push_stop_notification (cs
.last_ptid
, &cs
.last_status
);
4468 /* Be sure to not change the selected thread behind GDB's back.
4469 Important in the non-stop mode asynchronous protocol. */
4470 set_desired_thread ();
4483 } // namespace selftests
4484 #endif /* GDB_SELF_TEST */