Update gdb/NEWS after GDB 14 branch creation.
[binutils-gdb.git] / gdbserver / server.cc
blobe02cdb83b51a91a3c1f76a7e4b69c7f1dd7b1fd1
1 /* Main code for remote server for GDB.
2 Copyright (C) 1989-2023 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/>. */
19 #include "server.h"
20 #include "gdbthread.h"
21 #include "gdbsupport/agent.h"
22 #include "notif.h"
23 #include "tdesc.h"
24 #include "gdbsupport/rsp-low.h"
25 #include "gdbsupport/signals-state-save-restore.h"
26 #include <ctype.h>
27 #include <unistd.h>
28 #if HAVE_SIGNAL_H
29 #include <signal.h>
30 #endif
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"
36 #include "dll.h"
37 #include "hostio.h"
38 #include <vector>
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"
44 #ifdef USE_XML
45 #include "xml-builtin.h"
46 #endif
48 #include "gdbsupport/selftest.h"
49 #include "gdbsupport/scope-exit.h"
50 #include "gdbsupport/gdb_select.h"
51 #include "gdbsupport/scoped_restore.h"
52 #include "gdbsupport/search.h"
54 /* PBUFSIZ must also be at least as big as IPA_CMD_BUF_SIZE, because
55 the client state data is passed directly to some agent
56 functions. */
57 gdb_static_assert (PBUFSIZ >= IPA_CMD_BUF_SIZE);
59 #define require_running_or_return(BUF) \
60 if (!target_running ()) \
61 { \
62 write_enn (BUF); \
63 return; \
66 #define require_running_or_break(BUF) \
67 if (!target_running ()) \
68 { \
69 write_enn (BUF); \
70 break; \
73 /* The environment to pass to the inferior when creating it. */
75 static gdb_environ our_environ;
77 bool server_waiting;
79 static bool extended_protocol;
80 static bool response_needed;
81 static bool exit_requested;
83 /* --once: Exit after the first connection has closed. */
84 bool run_once;
86 /* Whether to report TARGET_WAITKIND_NO_RESUMED events. */
87 static bool report_no_resumed;
89 /* The event loop checks this to decide whether to continue accepting
90 events. */
91 static bool keep_processing_events = true;
93 bool non_stop;
95 static struct {
96 /* Set the PROGRAM_PATH. Here we adjust the path of the provided
97 binary if needed. */
98 void set (const char *path)
100 m_path = path;
102 /* Make sure we're using the absolute path of the inferior when
103 creating it. */
104 if (!contains_dir_separator (m_path.c_str ()))
106 int reg_file_errno;
108 /* Check if the file is in our CWD. If it is, then we prefix
109 its name with CURRENT_DIRECTORY. Otherwise, we leave the
110 name as-is because we'll try searching for it in $PATH. */
111 if (is_regular_file (m_path.c_str (), &reg_file_errno))
112 m_path = gdb_abspath (m_path.c_str ());
116 /* Return the PROGRAM_PATH. */
117 const char *get ()
118 { return m_path.empty () ? nullptr : m_path.c_str (); }
120 private:
121 /* The program name, adjusted if needed. */
122 std::string m_path;
123 } program_path;
124 static std::vector<char *> program_args;
125 static std::string wrapper_argv;
127 /* The PID of the originally created or attached inferior. Used to
128 send signals to the process when GDB sends us an asynchronous interrupt
129 (user hitting Control-C in the client), and to wait for the child to exit
130 when no longer debugging it. */
132 unsigned long signal_pid;
134 /* Set if you want to disable optional thread related packets support
135 in gdbserver, for the sake of testing GDB against stubs that don't
136 support them. */
137 bool disable_packet_vCont;
138 bool disable_packet_Tthread;
139 bool disable_packet_qC;
140 bool disable_packet_qfThreadInfo;
141 bool disable_packet_T;
143 static unsigned char *mem_buf;
145 /* A sub-class of 'struct notif_event' for stop, holding information
146 relative to a single stop reply. We keep a queue of these to
147 push to GDB in non-stop mode. */
149 struct vstop_notif : public notif_event
151 /* Thread or process that got the event. */
152 ptid_t ptid;
154 /* Event info. */
155 struct target_waitstatus status;
158 /* The current btrace configuration. This is gdbserver's mirror of GDB's
159 btrace configuration. */
160 static struct btrace_config current_btrace_conf;
162 /* The client remote protocol state. */
164 static client_state g_client_state;
166 client_state &
167 get_client_state ()
169 client_state &cs = g_client_state;
170 return cs;
174 /* Put a stop reply to the stop reply queue. */
176 static void
177 queue_stop_reply (ptid_t ptid, const target_waitstatus &status)
179 struct vstop_notif *new_notif = new struct vstop_notif;
181 new_notif->ptid = ptid;
182 new_notif->status = status;
184 notif_event_enque (&notif_stop, new_notif);
187 static bool
188 remove_all_on_match_ptid (struct notif_event *event, ptid_t filter_ptid)
190 struct vstop_notif *vstop_event = (struct vstop_notif *) event;
192 return vstop_event->ptid.matches (filter_ptid);
195 /* See server.h. */
197 void
198 discard_queued_stop_replies (ptid_t ptid)
200 std::list<notif_event *>::iterator iter, next, end;
201 end = notif_stop.queue.end ();
202 for (iter = notif_stop.queue.begin (); iter != end; iter = next)
204 next = iter;
205 ++next;
207 if (iter == notif_stop.queue.begin ())
209 /* The head of the list contains the notification that was
210 already sent to GDB. So we can't remove it, otherwise
211 when GDB sends the vStopped, it would ack the _next_
212 notification, which hadn't been sent yet! */
213 continue;
216 if (remove_all_on_match_ptid (*iter, ptid))
218 delete *iter;
219 notif_stop.queue.erase (iter);
224 static void
225 vstop_notif_reply (struct notif_event *event, char *own_buf)
227 struct vstop_notif *vstop = (struct vstop_notif *) event;
229 prepare_resume_reply (own_buf, vstop->ptid, vstop->status);
232 /* Helper for in_queued_stop_replies. */
234 static bool
235 in_queued_stop_replies_ptid (struct notif_event *event, ptid_t filter_ptid)
237 struct vstop_notif *vstop_event = (struct vstop_notif *) event;
239 if (vstop_event->ptid.matches (filter_ptid))
240 return true;
242 /* Don't resume fork children that GDB does not know about yet. */
243 if ((vstop_event->status.kind () == TARGET_WAITKIND_FORKED
244 || vstop_event->status.kind () == TARGET_WAITKIND_VFORKED)
245 && vstop_event->status.child_ptid ().matches (filter_ptid))
246 return true;
248 return false;
251 /* See server.h. */
254 in_queued_stop_replies (ptid_t ptid)
256 for (notif_event *event : notif_stop.queue)
258 if (in_queued_stop_replies_ptid (event, ptid))
259 return true;
262 return false;
265 struct notif_server notif_stop =
267 "vStopped", "Stop", {}, vstop_notif_reply,
270 static int
271 target_running (void)
273 return get_first_thread () != NULL;
276 /* See gdbsupport/common-inferior.h. */
278 const char *
279 get_exec_wrapper ()
281 return !wrapper_argv.empty () ? wrapper_argv.c_str () : NULL;
284 /* See gdbsupport/common-inferior.h. */
286 const char *
287 get_exec_file (int err)
289 if (err && program_path.get () == NULL)
290 error (_("No executable file specified."));
292 return program_path.get ();
295 /* See server.h. */
297 gdb_environ *
298 get_environ ()
300 return &our_environ;
303 static int
304 attach_inferior (int pid)
306 client_state &cs = get_client_state ();
307 /* myattach should return -1 if attaching is unsupported,
308 0 if it succeeded, and call error() otherwise. */
310 if (find_process_pid (pid) != nullptr)
311 error ("Already attached to process %d\n", pid);
313 if (myattach (pid) != 0)
314 return -1;
316 fprintf (stderr, "Attached; pid = %d\n", pid);
317 fflush (stderr);
319 /* FIXME - It may be that we should get the SIGNAL_PID from the
320 attach function, so that it can be the main thread instead of
321 whichever we were told to attach to. */
322 signal_pid = pid;
324 if (!non_stop)
326 cs.last_ptid = mywait (ptid_t (pid), &cs.last_status, 0, 0);
328 /* GDB knows to ignore the first SIGSTOP after attaching to a running
329 process using the "attach" command, but this is different; it's
330 just using "target remote". Pretend it's just starting up. */
331 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED
332 && cs.last_status.sig () == GDB_SIGNAL_STOP)
333 cs.last_status.set_stopped (GDB_SIGNAL_TRAP);
335 current_thread->last_resume_kind = resume_stop;
336 current_thread->last_status = cs.last_status;
339 return 0;
342 /* Decode a qXfer read request. Return 0 if everything looks OK,
343 or -1 otherwise. */
345 static int
346 decode_xfer_read (char *buf, CORE_ADDR *ofs, unsigned int *len)
348 /* After the read marker and annex, qXfer looks like a
349 traditional 'm' packet. */
350 decode_m_packet (buf, ofs, len);
352 return 0;
355 static int
356 decode_xfer (char *buf, char **object, char **rw, char **annex, char **offset)
358 /* Extract and NUL-terminate the object. */
359 *object = buf;
360 while (*buf && *buf != ':')
361 buf++;
362 if (*buf == '\0')
363 return -1;
364 *buf++ = 0;
366 /* Extract and NUL-terminate the read/write action. */
367 *rw = buf;
368 while (*buf && *buf != ':')
369 buf++;
370 if (*buf == '\0')
371 return -1;
372 *buf++ = 0;
374 /* Extract and NUL-terminate the annex. */
375 *annex = buf;
376 while (*buf && *buf != ':')
377 buf++;
378 if (*buf == '\0')
379 return -1;
380 *buf++ = 0;
382 *offset = buf;
383 return 0;
386 /* Write the response to a successful qXfer read. Returns the
387 length of the (binary) data stored in BUF, corresponding
388 to as much of DATA/LEN as we could fit. IS_MORE controls
389 the first character of the response. */
390 static int
391 write_qxfer_response (char *buf, const gdb_byte *data, int len, int is_more)
393 int out_len;
395 if (is_more)
396 buf[0] = 'm';
397 else
398 buf[0] = 'l';
400 return remote_escape_output (data, len, 1, (unsigned char *) buf + 1,
401 &out_len, PBUFSIZ - 2) + 1;
404 /* Handle btrace enabling in BTS format. */
406 static void
407 handle_btrace_enable_bts (struct thread_info *thread)
409 if (thread->btrace != NULL)
410 error (_("Btrace already enabled."));
412 current_btrace_conf.format = BTRACE_FORMAT_BTS;
413 thread->btrace = target_enable_btrace (thread, &current_btrace_conf);
416 /* Handle btrace enabling in Intel Processor Trace format. */
418 static void
419 handle_btrace_enable_pt (struct thread_info *thread)
421 if (thread->btrace != NULL)
422 error (_("Btrace already enabled."));
424 current_btrace_conf.format = BTRACE_FORMAT_PT;
425 thread->btrace = target_enable_btrace (thread, &current_btrace_conf);
428 /* Handle btrace disabling. */
430 static void
431 handle_btrace_disable (struct thread_info *thread)
434 if (thread->btrace == NULL)
435 error (_("Branch tracing not enabled."));
437 if (target_disable_btrace (thread->btrace) != 0)
438 error (_("Could not disable branch tracing."));
440 thread->btrace = NULL;
443 /* Handle the "Qbtrace" packet. */
445 static int
446 handle_btrace_general_set (char *own_buf)
448 client_state &cs = get_client_state ();
449 struct thread_info *thread;
450 char *op;
452 if (!startswith (own_buf, "Qbtrace:"))
453 return 0;
455 op = own_buf + strlen ("Qbtrace:");
457 if (cs.general_thread == null_ptid
458 || cs.general_thread == minus_one_ptid)
460 strcpy (own_buf, "E.Must select a single thread.");
461 return -1;
464 thread = find_thread_ptid (cs.general_thread);
465 if (thread == NULL)
467 strcpy (own_buf, "E.No such thread.");
468 return -1;
473 if (strcmp (op, "bts") == 0)
474 handle_btrace_enable_bts (thread);
475 else if (strcmp (op, "pt") == 0)
476 handle_btrace_enable_pt (thread);
477 else if (strcmp (op, "off") == 0)
478 handle_btrace_disable (thread);
479 else
480 error (_("Bad Qbtrace operation. Use bts, pt, or off."));
482 write_ok (own_buf);
484 catch (const gdb_exception_error &exception)
486 sprintf (own_buf, "E.%s", exception.what ());
489 return 1;
492 /* Handle the "Qbtrace-conf" packet. */
494 static int
495 handle_btrace_conf_general_set (char *own_buf)
497 client_state &cs = get_client_state ();
498 struct thread_info *thread;
499 char *op;
501 if (!startswith (own_buf, "Qbtrace-conf:"))
502 return 0;
504 op = own_buf + strlen ("Qbtrace-conf:");
506 if (cs.general_thread == null_ptid
507 || cs.general_thread == minus_one_ptid)
509 strcpy (own_buf, "E.Must select a single thread.");
510 return -1;
513 thread = find_thread_ptid (cs.general_thread);
514 if (thread == NULL)
516 strcpy (own_buf, "E.No such thread.");
517 return -1;
520 if (startswith (op, "bts:size="))
522 unsigned long size;
523 char *endp = NULL;
525 errno = 0;
526 size = strtoul (op + strlen ("bts:size="), &endp, 16);
527 if (endp == NULL || *endp != 0 || errno != 0 || size > UINT_MAX)
529 strcpy (own_buf, "E.Bad size value.");
530 return -1;
533 current_btrace_conf.bts.size = (unsigned int) size;
535 else if (strncmp (op, "pt:size=", strlen ("pt:size=")) == 0)
537 unsigned long size;
538 char *endp = NULL;
540 errno = 0;
541 size = strtoul (op + strlen ("pt:size="), &endp, 16);
542 if (endp == NULL || *endp != 0 || errno != 0 || size > UINT_MAX)
544 strcpy (own_buf, "E.Bad size value.");
545 return -1;
548 current_btrace_conf.pt.size = (unsigned int) size;
550 else
552 strcpy (own_buf, "E.Bad Qbtrace configuration option.");
553 return -1;
556 write_ok (own_buf);
557 return 1;
560 /* Create the qMemTags packet reply given TAGS.
562 Returns true if parsing succeeded and false otherwise. */
564 static bool
565 create_fetch_memtags_reply (char *reply, const gdb::byte_vector &tags)
567 /* It is an error to pass a zero-sized tag vector. */
568 gdb_assert (tags.size () != 0);
570 std::string packet ("m");
572 /* Write the tag data. */
573 packet += bin2hex (tags.data (), tags.size ());
575 /* Check if the reply is too big for the packet to handle. */
576 if (PBUFSIZ < packet.size ())
577 return false;
579 strcpy (reply, packet.c_str ());
580 return true;
583 /* Parse the QMemTags request into ADDR, LEN and TAGS.
585 Returns true if parsing succeeded and false otherwise. */
587 static bool
588 parse_store_memtags_request (char *request, CORE_ADDR *addr, size_t *len,
589 gdb::byte_vector &tags, int *type)
591 gdb_assert (startswith (request, "QMemTags:"));
593 const char *p = request + strlen ("QMemTags:");
595 /* Read address and length. */
596 unsigned int length = 0;
597 p = decode_m_packet_params (p, addr, &length, ':');
598 *len = length;
600 /* Read the tag type. */
601 ULONGEST tag_type = 0;
602 p = unpack_varlen_hex (p, &tag_type);
603 *type = (int) tag_type;
605 /* Make sure there is a colon after the type. */
606 if (*p != ':')
607 return false;
609 /* Skip the colon. */
610 p++;
612 /* Read the tag data. */
613 tags = hex2bin (p);
615 return true;
618 /* Handle all of the extended 'Q' packets. */
620 static void
621 handle_general_set (char *own_buf)
623 client_state &cs = get_client_state ();
624 if (startswith (own_buf, "QPassSignals:"))
626 int numsigs = (int) GDB_SIGNAL_LAST, i;
627 const char *p = own_buf + strlen ("QPassSignals:");
628 CORE_ADDR cursig;
630 p = decode_address_to_semicolon (&cursig, p);
631 for (i = 0; i < numsigs; i++)
633 if (i == cursig)
635 cs.pass_signals[i] = 1;
636 if (*p == '\0')
637 /* Keep looping, to clear the remaining signals. */
638 cursig = -1;
639 else
640 p = decode_address_to_semicolon (&cursig, p);
642 else
643 cs.pass_signals[i] = 0;
645 strcpy (own_buf, "OK");
646 return;
649 if (startswith (own_buf, "QProgramSignals:"))
651 int numsigs = (int) GDB_SIGNAL_LAST, i;
652 const char *p = own_buf + strlen ("QProgramSignals:");
653 CORE_ADDR cursig;
655 cs.program_signals_p = 1;
657 p = decode_address_to_semicolon (&cursig, p);
658 for (i = 0; i < numsigs; i++)
660 if (i == cursig)
662 cs.program_signals[i] = 1;
663 if (*p == '\0')
664 /* Keep looping, to clear the remaining signals. */
665 cursig = -1;
666 else
667 p = decode_address_to_semicolon (&cursig, p);
669 else
670 cs.program_signals[i] = 0;
672 strcpy (own_buf, "OK");
673 return;
676 if (startswith (own_buf, "QCatchSyscalls:"))
678 const char *p = own_buf + sizeof ("QCatchSyscalls:") - 1;
679 int enabled = -1;
680 CORE_ADDR sysno;
681 struct process_info *process;
683 if (!target_running () || !target_supports_catch_syscall ())
685 write_enn (own_buf);
686 return;
689 if (strcmp (p, "0") == 0)
690 enabled = 0;
691 else if (p[0] == '1' && (p[1] == ';' || p[1] == '\0'))
692 enabled = 1;
693 else
695 fprintf (stderr, "Unknown catch-syscalls mode requested: %s\n",
696 own_buf);
697 write_enn (own_buf);
698 return;
701 process = current_process ();
702 process->syscalls_to_catch.clear ();
704 if (enabled)
706 p += 1;
707 if (*p == ';')
709 p += 1;
710 while (*p != '\0')
712 p = decode_address_to_semicolon (&sysno, p);
713 process->syscalls_to_catch.push_back (sysno);
716 else
717 process->syscalls_to_catch.push_back (ANY_SYSCALL);
720 write_ok (own_buf);
721 return;
724 if (strcmp (own_buf, "QEnvironmentReset") == 0)
726 our_environ = gdb_environ::from_host_environ ();
728 write_ok (own_buf);
729 return;
732 if (startswith (own_buf, "QEnvironmentHexEncoded:"))
734 const char *p = own_buf + sizeof ("QEnvironmentHexEncoded:") - 1;
735 /* The final form of the environment variable. FINAL_VAR will
736 hold the 'VAR=VALUE' format. */
737 std::string final_var = hex2str (p);
738 std::string var_name, var_value;
740 remote_debug_printf ("[QEnvironmentHexEncoded received '%s']", p);
741 remote_debug_printf ("[Environment variable to be set: '%s']",
742 final_var.c_str ());
744 size_t pos = final_var.find ('=');
745 if (pos == std::string::npos)
747 warning (_("Unexpected format for environment variable: '%s'"),
748 final_var.c_str ());
749 write_enn (own_buf);
750 return;
753 var_name = final_var.substr (0, pos);
754 var_value = final_var.substr (pos + 1, std::string::npos);
756 our_environ.set (var_name.c_str (), var_value.c_str ());
758 write_ok (own_buf);
759 return;
762 if (startswith (own_buf, "QEnvironmentUnset:"))
764 const char *p = own_buf + sizeof ("QEnvironmentUnset:") - 1;
765 std::string varname = hex2str (p);
767 remote_debug_printf ("[QEnvironmentUnset received '%s']", p);
768 remote_debug_printf ("[Environment variable to be unset: '%s']",
769 varname.c_str ());
771 our_environ.unset (varname.c_str ());
773 write_ok (own_buf);
774 return;
777 if (strcmp (own_buf, "QStartNoAckMode") == 0)
779 remote_debug_printf ("[noack mode enabled]");
781 cs.noack_mode = 1;
782 write_ok (own_buf);
783 return;
786 if (startswith (own_buf, "QNonStop:"))
788 char *mode = own_buf + 9;
789 int req = -1;
790 const char *req_str;
792 if (strcmp (mode, "0") == 0)
793 req = 0;
794 else if (strcmp (mode, "1") == 0)
795 req = 1;
796 else
798 /* We don't know what this mode is, so complain to
799 GDB. */
800 fprintf (stderr, "Unknown non-stop mode requested: %s\n",
801 own_buf);
802 write_enn (own_buf);
803 return;
806 req_str = req ? "non-stop" : "all-stop";
807 if (the_target->start_non_stop (req == 1) != 0)
809 fprintf (stderr, "Setting %s mode failed\n", req_str);
810 write_enn (own_buf);
811 return;
814 non_stop = (req != 0);
816 remote_debug_printf ("[%s mode enabled]", req_str);
818 write_ok (own_buf);
819 return;
822 if (startswith (own_buf, "QDisableRandomization:"))
824 char *packet = own_buf + strlen ("QDisableRandomization:");
825 ULONGEST setting;
827 unpack_varlen_hex (packet, &setting);
828 cs.disable_randomization = setting;
830 remote_debug_printf (cs.disable_randomization
831 ? "[address space randomization disabled]"
832 : "[address space randomization enabled]");
834 write_ok (own_buf);
835 return;
838 if (target_supports_tracepoints ()
839 && handle_tracepoint_general_set (own_buf))
840 return;
842 if (startswith (own_buf, "QAgent:"))
844 char *mode = own_buf + strlen ("QAgent:");
845 int req = 0;
847 if (strcmp (mode, "0") == 0)
848 req = 0;
849 else if (strcmp (mode, "1") == 0)
850 req = 1;
851 else
853 /* We don't know what this value is, so complain to GDB. */
854 sprintf (own_buf, "E.Unknown QAgent value");
855 return;
858 /* Update the flag. */
859 use_agent = req;
860 remote_debug_printf ("[%s agent]", req ? "Enable" : "Disable");
861 write_ok (own_buf);
862 return;
865 if (handle_btrace_general_set (own_buf))
866 return;
868 if (handle_btrace_conf_general_set (own_buf))
869 return;
871 if (startswith (own_buf, "QThreadEvents:"))
873 char *mode = own_buf + strlen ("QThreadEvents:");
874 enum tribool req = TRIBOOL_UNKNOWN;
876 if (strcmp (mode, "0") == 0)
877 req = TRIBOOL_FALSE;
878 else if (strcmp (mode, "1") == 0)
879 req = TRIBOOL_TRUE;
880 else
882 /* We don't know what this mode is, so complain to GDB. */
883 std::string err
884 = string_printf ("E.Unknown thread-events mode requested: %s\n",
885 mode);
886 strcpy (own_buf, err.c_str ());
887 return;
890 cs.report_thread_events = (req == TRIBOOL_TRUE);
892 remote_debug_printf ("[thread events are now %s]\n",
893 cs.report_thread_events ? "enabled" : "disabled");
895 write_ok (own_buf);
896 return;
899 if (startswith (own_buf, "QStartupWithShell:"))
901 const char *value = own_buf + strlen ("QStartupWithShell:");
903 if (strcmp (value, "1") == 0)
904 startup_with_shell = true;
905 else if (strcmp (value, "0") == 0)
906 startup_with_shell = false;
907 else
909 /* Unknown value. */
910 fprintf (stderr, "Unknown value to startup-with-shell: %s\n",
911 own_buf);
912 write_enn (own_buf);
913 return;
916 remote_debug_printf ("[Inferior will %s started with shell]",
917 startup_with_shell ? "be" : "not be");
919 write_ok (own_buf);
920 return;
923 if (startswith (own_buf, "QSetWorkingDir:"))
925 const char *p = own_buf + strlen ("QSetWorkingDir:");
927 if (*p != '\0')
929 std::string path = hex2str (p);
931 remote_debug_printf ("[Set the inferior's current directory to %s]",
932 path.c_str ());
934 set_inferior_cwd (std::move (path));
936 else
938 /* An empty argument means that we should clear out any
939 previously set cwd for the inferior. */
940 set_inferior_cwd ("");
942 remote_debug_printf ("[Unset the inferior's current directory; will "
943 "use gdbserver's cwd]");
945 write_ok (own_buf);
947 return;
951 /* Handle store memory tags packets. */
952 if (startswith (own_buf, "QMemTags:")
953 && target_supports_memory_tagging ())
955 gdb::byte_vector tags;
956 CORE_ADDR addr = 0;
957 size_t len = 0;
958 int type = 0;
960 require_running_or_return (own_buf);
962 bool ret = parse_store_memtags_request (own_buf, &addr, &len, tags,
963 &type);
965 if (ret)
966 ret = the_target->store_memtags (addr, len, tags, type);
968 if (!ret)
969 write_enn (own_buf);
970 else
971 write_ok (own_buf);
973 return;
976 /* Otherwise we didn't know what packet it was. Say we didn't
977 understand it. */
978 own_buf[0] = 0;
981 static const char *
982 get_features_xml (const char *annex)
984 const struct target_desc *desc = current_target_desc ();
986 /* `desc->xmltarget' defines what to return when looking for the
987 "target.xml" file. Its contents can either be verbatim XML code
988 (prefixed with a '@') or else the name of the actual XML file to
989 be used in place of "target.xml".
991 This variable is set up from the auto-generated
992 init_registers_... routine for the current target. */
994 if (strcmp (annex, "target.xml") == 0)
996 const char *ret = tdesc_get_features_xml (desc);
998 if (*ret == '@')
999 return ret + 1;
1000 else
1001 annex = ret;
1004 #ifdef USE_XML
1006 int i;
1008 /* Look for the annex. */
1009 for (i = 0; xml_builtin[i][0] != NULL; i++)
1010 if (strcmp (annex, xml_builtin[i][0]) == 0)
1011 break;
1013 if (xml_builtin[i][0] != NULL)
1014 return xml_builtin[i][1];
1016 #endif
1018 return NULL;
1021 static void
1022 monitor_show_help (void)
1024 monitor_output ("The following monitor commands are supported:\n");
1025 monitor_output (" set debug <0|1>\n");
1026 monitor_output (" Enable general debugging messages\n");
1027 monitor_output (" set debug-hw-points <0|1>\n");
1028 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
1029 monitor_output (" set remote-debug <0|1>\n");
1030 monitor_output (" Enable remote protocol debugging messages\n");
1031 monitor_output (" set event-loop-debug <0|1>\n");
1032 monitor_output (" Enable event loop debugging messages\n");
1033 monitor_output (" set debug-format option1[,option2,...]\n");
1034 monitor_output (" Add additional information to debugging messages\n");
1035 monitor_output (" Options: all, none");
1036 monitor_output (", timestamp");
1037 monitor_output ("\n");
1038 monitor_output (" exit\n");
1039 monitor_output (" Quit GDBserver\n");
1042 /* Read trace frame or inferior memory. Returns the number of bytes
1043 actually read, zero when no further transfer is possible, and -1 on
1044 error. Return of a positive value smaller than LEN does not
1045 indicate there's no more to be read, only the end of the transfer.
1046 E.g., when GDB reads memory from a traceframe, a first request may
1047 be served from a memory block that does not cover the whole request
1048 length. A following request gets the rest served from either
1049 another block (of the same traceframe) or from the read-only
1050 regions. */
1052 static int
1053 gdb_read_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
1055 client_state &cs = get_client_state ();
1056 int res;
1058 if (cs.current_traceframe >= 0)
1060 ULONGEST nbytes;
1061 ULONGEST length = len;
1063 if (traceframe_read_mem (cs.current_traceframe,
1064 memaddr, myaddr, len, &nbytes))
1065 return -1;
1066 /* Data read from trace buffer, we're done. */
1067 if (nbytes > 0)
1068 return nbytes;
1069 if (!in_readonly_region (memaddr, length))
1070 return -1;
1071 /* Otherwise we have a valid readonly case, fall through. */
1072 /* (assume no half-trace half-real blocks for now) */
1075 if (set_desired_process ())
1076 res = read_inferior_memory (memaddr, myaddr, len);
1077 else
1078 res = 1;
1080 return res == 0 ? len : -1;
1083 /* Write trace frame or inferior memory. Actually, writing to trace
1084 frames is forbidden. */
1086 static int
1087 gdb_write_memory (CORE_ADDR memaddr, const unsigned char *myaddr, int len)
1089 client_state &cs = get_client_state ();
1090 if (cs.current_traceframe >= 0)
1091 return EIO;
1092 else
1094 int ret;
1096 if (set_desired_process ())
1097 ret = target_write_memory (memaddr, myaddr, len);
1098 else
1099 ret = EIO;
1100 return ret;
1104 /* Handle qSearch:memory packets. */
1106 static void
1107 handle_search_memory (char *own_buf, int packet_len)
1109 CORE_ADDR start_addr;
1110 CORE_ADDR search_space_len;
1111 gdb_byte *pattern;
1112 unsigned int pattern_len;
1113 int found;
1114 CORE_ADDR found_addr;
1115 int cmd_name_len = sizeof ("qSearch:memory:") - 1;
1117 pattern = (gdb_byte *) malloc (packet_len);
1118 if (pattern == NULL)
1119 error ("Unable to allocate memory to perform the search");
1121 if (decode_search_memory_packet (own_buf + cmd_name_len,
1122 packet_len - cmd_name_len,
1123 &start_addr, &search_space_len,
1124 pattern, &pattern_len) < 0)
1126 free (pattern);
1127 error ("Error in parsing qSearch:memory packet");
1130 auto read_memory = [] (CORE_ADDR addr, gdb_byte *result, size_t len)
1132 return gdb_read_memory (addr, result, len) == len;
1135 found = simple_search_memory (read_memory, start_addr, search_space_len,
1136 pattern, pattern_len, &found_addr);
1138 if (found > 0)
1139 sprintf (own_buf, "1,%lx", (long) found_addr);
1140 else if (found == 0)
1141 strcpy (own_buf, "0");
1142 else
1143 strcpy (own_buf, "E00");
1145 free (pattern);
1148 /* Handle the "D" packet. */
1150 static void
1151 handle_detach (char *own_buf)
1153 client_state &cs = get_client_state ();
1155 process_info *process;
1157 if (cs.multi_process)
1159 /* skip 'D;' */
1160 int pid = strtol (&own_buf[2], NULL, 16);
1162 process = find_process_pid (pid);
1164 else
1166 process = (current_thread != nullptr
1167 ? get_thread_process (current_thread)
1168 : nullptr);
1171 if (process == NULL)
1173 write_enn (own_buf);
1174 return;
1177 if ((tracing && disconnected_tracing) || any_persistent_commands (process))
1179 if (tracing && disconnected_tracing)
1180 fprintf (stderr,
1181 "Disconnected tracing in effect, "
1182 "leaving gdbserver attached to the process\n");
1184 if (any_persistent_commands (process))
1185 fprintf (stderr,
1186 "Persistent commands are present, "
1187 "leaving gdbserver attached to the process\n");
1189 /* Make sure we're in non-stop/async mode, so we we can both
1190 wait for an async socket accept, and handle async target
1191 events simultaneously. There's also no point either in
1192 having the target stop all threads, when we're going to
1193 pass signals down without informing GDB. */
1194 if (!non_stop)
1196 threads_debug_printf ("Forcing non-stop mode");
1198 non_stop = true;
1199 the_target->start_non_stop (true);
1202 process->gdb_detached = 1;
1204 /* Detaching implicitly resumes all threads. */
1205 target_continue_no_signal (minus_one_ptid);
1207 write_ok (own_buf);
1208 return;
1211 fprintf (stderr, "Detaching from process %d\n", process->pid);
1212 stop_tracing ();
1214 /* We'll need this after PROCESS has been destroyed. */
1215 int pid = process->pid;
1217 /* If this process has an unreported fork child, that child is not known to
1218 GDB, so GDB won't take care of detaching it. We must do it here.
1220 Here, we specifically don't want to use "safe iteration", as detaching
1221 another process might delete the next thread in the iteration, which is
1222 the one saved by the safe iterator. We will never delete the currently
1223 iterated on thread, so standard iteration should be safe. */
1224 for (thread_info *thread : all_threads)
1226 /* Only threads that are of the process we are detaching. */
1227 if (thread->id.pid () != pid)
1228 continue;
1230 /* Only threads that have a pending fork event. */
1231 thread_info *child = target_thread_pending_child (thread);
1232 if (child == nullptr)
1233 continue;
1235 process_info *fork_child_process = get_thread_process (child);
1236 gdb_assert (fork_child_process != nullptr);
1238 int fork_child_pid = fork_child_process->pid;
1240 if (detach_inferior (fork_child_process) != 0)
1241 warning (_("Failed to detach fork child %s, child of %s"),
1242 target_pid_to_str (ptid_t (fork_child_pid)).c_str (),
1243 target_pid_to_str (thread->id).c_str ());
1246 if (detach_inferior (process) != 0)
1247 write_enn (own_buf);
1248 else
1250 discard_queued_stop_replies (ptid_t (pid));
1251 write_ok (own_buf);
1253 if (extended_protocol || target_running ())
1255 /* There is still at least one inferior remaining or
1256 we are in extended mode, so don't terminate gdbserver,
1257 and instead treat this like a normal program exit. */
1258 cs.last_status.set_exited (0);
1259 cs.last_ptid = ptid_t (pid);
1261 switch_to_thread (nullptr);
1263 else
1265 putpkt (own_buf);
1266 remote_close ();
1268 /* If we are attached, then we can exit. Otherwise, we
1269 need to hang around doing nothing, until the child is
1270 gone. */
1271 join_inferior (pid);
1272 exit (0);
1277 /* Parse options to --debug-format= and "monitor set debug-format".
1278 ARG is the text after "--debug-format=" or "monitor set debug-format".
1279 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1280 This triggers calls to monitor_output.
1281 The result is an empty string if all options were parsed ok, otherwise an
1282 error message which the caller must free.
1284 N.B. These commands affect all debug format settings, they are not
1285 cumulative. If a format is not specified, it is turned off.
1286 However, we don't go to extra trouble with things like
1287 "monitor set debug-format all,none,timestamp".
1288 Instead we just parse them one at a time, in order.
1290 The syntax for "monitor set debug" we support here is not identical
1291 to gdb's "set debug foo on|off" because we also use this function to
1292 parse "--debug-format=foo,bar". */
1294 static std::string
1295 parse_debug_format_options (const char *arg, int is_monitor)
1297 /* First turn all debug format options off. */
1298 debug_timestamp = 0;
1300 /* First remove leading spaces, for "monitor set debug-format". */
1301 while (isspace (*arg))
1302 ++arg;
1304 std::vector<gdb::unique_xmalloc_ptr<char>> options
1305 = delim_string_to_char_ptr_vec (arg, ',');
1307 for (const gdb::unique_xmalloc_ptr<char> &option : options)
1309 if (strcmp (option.get (), "all") == 0)
1311 debug_timestamp = 1;
1312 if (is_monitor)
1313 monitor_output ("All extra debug format options enabled.\n");
1315 else if (strcmp (option.get (), "none") == 0)
1317 debug_timestamp = 0;
1318 if (is_monitor)
1319 monitor_output ("All extra debug format options disabled.\n");
1321 else if (strcmp (option.get (), "timestamp") == 0)
1323 debug_timestamp = 1;
1324 if (is_monitor)
1325 monitor_output ("Timestamps will be added to debug output.\n");
1327 else if (*option == '\0')
1329 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1330 continue;
1332 else
1333 return string_printf ("Unknown debug-format argument: \"%s\"\n",
1334 option.get ());
1337 return std::string ();
1340 /* Handle monitor commands not handled by target-specific handlers. */
1342 static void
1343 handle_monitor_command (char *mon, char *own_buf)
1345 if (strcmp (mon, "set debug 1") == 0)
1347 debug_threads = true;
1348 monitor_output ("Debug output enabled.\n");
1350 else if (strcmp (mon, "set debug 0") == 0)
1352 debug_threads = false;
1353 monitor_output ("Debug output disabled.\n");
1355 else if (strcmp (mon, "set debug-hw-points 1") == 0)
1357 show_debug_regs = 1;
1358 monitor_output ("H/W point debugging output enabled.\n");
1360 else if (strcmp (mon, "set debug-hw-points 0") == 0)
1362 show_debug_regs = 0;
1363 monitor_output ("H/W point debugging output disabled.\n");
1365 else if (strcmp (mon, "set remote-debug 1") == 0)
1367 remote_debug = true;
1368 monitor_output ("Protocol debug output enabled.\n");
1370 else if (strcmp (mon, "set remote-debug 0") == 0)
1372 remote_debug = false;
1373 monitor_output ("Protocol debug output disabled.\n");
1375 else if (strcmp (mon, "set event-loop-debug 1") == 0)
1377 debug_event_loop = debug_event_loop_kind::ALL;
1378 monitor_output ("Event loop debug output enabled.\n");
1380 else if (strcmp (mon, "set event-loop-debug 0") == 0)
1382 debug_event_loop = debug_event_loop_kind::OFF;
1383 monitor_output ("Event loop 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;
1406 else
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. */
1416 struct qxfer
1418 /* The object this handler handles. */
1419 const char *object;
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. */
1440 static int
1441 handle_qxfer_auxv (const char *annex,
1442 gdb_byte *readbuf, const gdb_byte *writebuf,
1443 ULONGEST offset, LONGEST len)
1445 if (!the_target->supports_read_auxv () || writebuf != NULL)
1446 return -2;
1448 if (annex[0] != '\0' || current_thread == NULL)
1449 return -1;
1451 return the_target->read_auxv (current_thread->id.pid (), offset, readbuf,
1452 len);
1455 /* Handle qXfer:exec-file:read. */
1457 static int
1458 handle_qxfer_exec_file (const char *annex,
1459 gdb_byte *readbuf, const gdb_byte *writebuf,
1460 ULONGEST offset, LONGEST len)
1462 ULONGEST pid;
1463 int total_len;
1465 if (!the_target->supports_pid_to_exec_file () || writebuf != NULL)
1466 return -2;
1468 if (annex[0] == '\0')
1470 if (current_thread == NULL)
1471 return -1;
1473 pid = pid_of (current_thread);
1475 else
1477 annex = unpack_varlen_hex (annex, &pid);
1478 if (annex[0] != '\0')
1479 return -1;
1482 if (pid <= 0)
1483 return -1;
1485 const char *file = the_target->pid_to_exec_file (pid);
1486 if (file == NULL)
1487 return -1;
1489 total_len = strlen (file);
1491 if (offset > total_len)
1492 return -1;
1494 if (offset + len > total_len)
1495 len = total_len - offset;
1497 memcpy (readbuf, file + offset, len);
1498 return len;
1501 /* Handle qXfer:features:read. */
1503 static int
1504 handle_qxfer_features (const char *annex,
1505 gdb_byte *readbuf, const gdb_byte *writebuf,
1506 ULONGEST offset, LONGEST len)
1508 const char *document;
1509 size_t total_len;
1511 if (writebuf != NULL)
1512 return -2;
1514 if (!target_running ())
1515 return -1;
1517 /* Grab the correct annex. */
1518 document = get_features_xml (annex);
1519 if (document == NULL)
1520 return -1;
1522 total_len = strlen (document);
1524 if (offset > total_len)
1525 return -1;
1527 if (offset + len > total_len)
1528 len = total_len - offset;
1530 memcpy (readbuf, document + offset, len);
1531 return len;
1534 /* Handle qXfer:libraries:read. */
1536 static int
1537 handle_qxfer_libraries (const char *annex,
1538 gdb_byte *readbuf, const gdb_byte *writebuf,
1539 ULONGEST offset, LONGEST len)
1541 if (writebuf != NULL)
1542 return -2;
1544 if (annex[0] != '\0' || current_thread == NULL)
1545 return -1;
1547 std::string document = "<library-list version=\"1.0\">\n";
1549 process_info *proc = current_process ();
1550 for (const dll_info &dll : proc->all_dlls)
1551 document += string_printf
1552 (" <library name=\"%s\"><segment address=\"0x%s\"/></library>\n",
1553 dll.name.c_str (), paddress (dll.base_addr));
1555 document += "</library-list>\n";
1557 if (offset > document.length ())
1558 return -1;
1560 if (offset + len > document.length ())
1561 len = document.length () - offset;
1563 memcpy (readbuf, &document[offset], len);
1565 return len;
1568 /* Handle qXfer:libraries-svr4:read. */
1570 static int
1571 handle_qxfer_libraries_svr4 (const char *annex,
1572 gdb_byte *readbuf, const gdb_byte *writebuf,
1573 ULONGEST offset, LONGEST len)
1575 if (writebuf != NULL)
1576 return -2;
1578 if (current_thread == NULL
1579 || !the_target->supports_qxfer_libraries_svr4 ())
1580 return -1;
1582 return the_target->qxfer_libraries_svr4 (annex, readbuf, writebuf,
1583 offset, len);
1586 /* Handle qXfer:osadata:read. */
1588 static int
1589 handle_qxfer_osdata (const char *annex,
1590 gdb_byte *readbuf, const gdb_byte *writebuf,
1591 ULONGEST offset, LONGEST len)
1593 if (!the_target->supports_qxfer_osdata () || writebuf != NULL)
1594 return -2;
1596 return the_target->qxfer_osdata (annex, readbuf, NULL, offset, len);
1599 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1601 static int
1602 handle_qxfer_siginfo (const char *annex,
1603 gdb_byte *readbuf, const gdb_byte *writebuf,
1604 ULONGEST offset, LONGEST len)
1606 if (!the_target->supports_qxfer_siginfo ())
1607 return -2;
1609 if (annex[0] != '\0' || current_thread == NULL)
1610 return -1;
1612 return the_target->qxfer_siginfo (annex, readbuf, writebuf, offset, len);
1615 /* Handle qXfer:statictrace:read. */
1617 static int
1618 handle_qxfer_statictrace (const char *annex,
1619 gdb_byte *readbuf, const gdb_byte *writebuf,
1620 ULONGEST offset, LONGEST len)
1622 client_state &cs = get_client_state ();
1623 ULONGEST nbytes;
1625 if (writebuf != NULL)
1626 return -2;
1628 if (annex[0] != '\0' || current_thread == NULL
1629 || cs.current_traceframe == -1)
1630 return -1;
1632 if (traceframe_read_sdata (cs.current_traceframe, offset,
1633 readbuf, len, &nbytes))
1634 return -1;
1635 return nbytes;
1638 /* Helper for handle_qxfer_threads_proper.
1639 Emit the XML to describe the thread of INF. */
1641 static void
1642 handle_qxfer_threads_worker (thread_info *thread, std::string *buffer)
1644 ptid_t ptid = ptid_of (thread);
1645 char ptid_s[100];
1646 int core = target_core_of_thread (ptid);
1647 char core_s[21];
1648 const char *name = target_thread_name (ptid);
1649 int handle_len;
1650 gdb_byte *handle;
1651 bool handle_status = target_thread_handle (ptid, &handle, &handle_len);
1653 /* If this is a fork or vfork child (has a fork parent), GDB does not yet
1654 know about this process, and must not know about it until it gets the
1655 corresponding (v)fork event. Exclude this thread from the list. */
1656 if (target_thread_pending_parent (thread) != nullptr)
1657 return;
1659 write_ptid (ptid_s, ptid);
1661 string_xml_appendf (*buffer, "<thread id=\"%s\"", ptid_s);
1663 if (core != -1)
1665 sprintf (core_s, "%d", core);
1666 string_xml_appendf (*buffer, " core=\"%s\"", core_s);
1669 if (name != NULL)
1670 string_xml_appendf (*buffer, " name=\"%s\"", name);
1672 if (handle_status)
1674 char *handle_s = (char *) alloca (handle_len * 2 + 1);
1675 bin2hex (handle, handle_s, handle_len);
1676 string_xml_appendf (*buffer, " handle=\"%s\"", handle_s);
1679 string_xml_appendf (*buffer, "/>\n");
1682 /* Helper for handle_qxfer_threads. Return true on success, false
1683 otherwise. */
1685 static bool
1686 handle_qxfer_threads_proper (std::string *buffer)
1688 *buffer += "<threads>\n";
1690 /* The target may need to access memory and registers (e.g. via
1691 libthread_db) to fetch thread properties. Even if don't need to
1692 stop threads to access memory, we still will need to be able to
1693 access registers, and other ptrace accesses like
1694 PTRACE_GET_THREAD_AREA that require a paused thread. Pause all
1695 threads here, so that we pause each thread at most once for all
1696 accesses. */
1697 if (non_stop)
1698 target_pause_all (true);
1700 for_each_thread ([&] (thread_info *thread)
1702 handle_qxfer_threads_worker (thread, buffer);
1705 if (non_stop)
1706 target_unpause_all (true);
1708 *buffer += "</threads>\n";
1709 return true;
1712 /* Handle qXfer:threads:read. */
1714 static int
1715 handle_qxfer_threads (const char *annex,
1716 gdb_byte *readbuf, const gdb_byte *writebuf,
1717 ULONGEST offset, LONGEST len)
1719 static std::string result;
1721 if (writebuf != NULL)
1722 return -2;
1724 if (annex[0] != '\0')
1725 return -1;
1727 if (offset == 0)
1729 /* When asked for data at offset 0, generate everything and store into
1730 'result'. Successive reads will be served off 'result'. */
1731 result.clear ();
1733 bool res = handle_qxfer_threads_proper (&result);
1735 if (!res)
1736 return -1;
1739 if (offset >= result.length ())
1741 /* We're out of data. */
1742 result.clear ();
1743 return 0;
1746 if (len > result.length () - offset)
1747 len = result.length () - offset;
1749 memcpy (readbuf, result.c_str () + offset, len);
1751 return len;
1754 /* Handle qXfer:traceframe-info:read. */
1756 static int
1757 handle_qxfer_traceframe_info (const char *annex,
1758 gdb_byte *readbuf, const gdb_byte *writebuf,
1759 ULONGEST offset, LONGEST len)
1761 client_state &cs = get_client_state ();
1762 static std::string result;
1764 if (writebuf != NULL)
1765 return -2;
1767 if (!target_running () || annex[0] != '\0' || cs.current_traceframe == -1)
1768 return -1;
1770 if (offset == 0)
1772 /* When asked for data at offset 0, generate everything and
1773 store into 'result'. Successive reads will be served off
1774 'result'. */
1775 result.clear ();
1777 traceframe_read_info (cs.current_traceframe, &result);
1780 if (offset >= result.length ())
1782 /* We're out of data. */
1783 result.clear ();
1784 return 0;
1787 if (len > result.length () - offset)
1788 len = result.length () - offset;
1790 memcpy (readbuf, result.c_str () + offset, len);
1791 return len;
1794 /* Handle qXfer:fdpic:read. */
1796 static int
1797 handle_qxfer_fdpic (const char *annex, gdb_byte *readbuf,
1798 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
1800 if (!the_target->supports_read_loadmap ())
1801 return -2;
1803 if (current_thread == NULL)
1804 return -1;
1806 return the_target->read_loadmap (annex, offset, readbuf, len);
1809 /* Handle qXfer:btrace:read. */
1811 static int
1812 handle_qxfer_btrace (const char *annex,
1813 gdb_byte *readbuf, const gdb_byte *writebuf,
1814 ULONGEST offset, LONGEST len)
1816 client_state &cs = get_client_state ();
1817 static std::string cache;
1818 struct thread_info *thread;
1819 enum btrace_read_type type;
1820 int result;
1822 if (writebuf != NULL)
1823 return -2;
1825 if (cs.general_thread == null_ptid
1826 || cs.general_thread == minus_one_ptid)
1828 strcpy (cs.own_buf, "E.Must select a single thread.");
1829 return -3;
1832 thread = find_thread_ptid (cs.general_thread);
1833 if (thread == NULL)
1835 strcpy (cs.own_buf, "E.No such thread.");
1836 return -3;
1839 if (thread->btrace == NULL)
1841 strcpy (cs.own_buf, "E.Btrace not enabled.");
1842 return -3;
1845 if (strcmp (annex, "all") == 0)
1846 type = BTRACE_READ_ALL;
1847 else if (strcmp (annex, "new") == 0)
1848 type = BTRACE_READ_NEW;
1849 else if (strcmp (annex, "delta") == 0)
1850 type = BTRACE_READ_DELTA;
1851 else
1853 strcpy (cs.own_buf, "E.Bad annex.");
1854 return -3;
1857 if (offset == 0)
1859 cache.clear ();
1863 result = target_read_btrace (thread->btrace, &cache, type);
1864 if (result != 0)
1865 memcpy (cs.own_buf, cache.c_str (), cache.length ());
1867 catch (const gdb_exception_error &exception)
1869 sprintf (cs.own_buf, "E.%s", exception.what ());
1870 result = -1;
1873 if (result != 0)
1874 return -3;
1876 else if (offset > cache.length ())
1878 cache.clear ();
1879 return -3;
1882 if (len > cache.length () - offset)
1883 len = cache.length () - offset;
1885 memcpy (readbuf, cache.c_str () + offset, len);
1887 return len;
1890 /* Handle qXfer:btrace-conf:read. */
1892 static int
1893 handle_qxfer_btrace_conf (const char *annex,
1894 gdb_byte *readbuf, const gdb_byte *writebuf,
1895 ULONGEST offset, LONGEST len)
1897 client_state &cs = get_client_state ();
1898 static std::string cache;
1899 struct thread_info *thread;
1900 int result;
1902 if (writebuf != NULL)
1903 return -2;
1905 if (annex[0] != '\0')
1906 return -1;
1908 if (cs.general_thread == null_ptid
1909 || cs.general_thread == minus_one_ptid)
1911 strcpy (cs.own_buf, "E.Must select a single thread.");
1912 return -3;
1915 thread = find_thread_ptid (cs.general_thread);
1916 if (thread == NULL)
1918 strcpy (cs.own_buf, "E.No such thread.");
1919 return -3;
1922 if (thread->btrace == NULL)
1924 strcpy (cs.own_buf, "E.Btrace not enabled.");
1925 return -3;
1928 if (offset == 0)
1930 cache.clear ();
1934 result = target_read_btrace_conf (thread->btrace, &cache);
1935 if (result != 0)
1936 memcpy (cs.own_buf, cache.c_str (), cache.length ());
1938 catch (const gdb_exception_error &exception)
1940 sprintf (cs.own_buf, "E.%s", exception.what ());
1941 result = -1;
1944 if (result != 0)
1945 return -3;
1947 else if (offset > cache.length ())
1949 cache.clear ();
1950 return -3;
1953 if (len > cache.length () - offset)
1954 len = cache.length () - offset;
1956 memcpy (readbuf, cache.c_str () + offset, len);
1958 return len;
1961 static const struct qxfer qxfer_packets[] =
1963 { "auxv", handle_qxfer_auxv },
1964 { "btrace", handle_qxfer_btrace },
1965 { "btrace-conf", handle_qxfer_btrace_conf },
1966 { "exec-file", handle_qxfer_exec_file},
1967 { "fdpic", handle_qxfer_fdpic},
1968 { "features", handle_qxfer_features },
1969 { "libraries", handle_qxfer_libraries },
1970 { "libraries-svr4", handle_qxfer_libraries_svr4 },
1971 { "osdata", handle_qxfer_osdata },
1972 { "siginfo", handle_qxfer_siginfo },
1973 { "statictrace", handle_qxfer_statictrace },
1974 { "threads", handle_qxfer_threads },
1975 { "traceframe-info", handle_qxfer_traceframe_info },
1978 static int
1979 handle_qxfer (char *own_buf, int packet_len, int *new_packet_len_p)
1981 int i;
1982 char *object;
1983 char *rw;
1984 char *annex;
1985 char *offset;
1987 if (!startswith (own_buf, "qXfer:"))
1988 return 0;
1990 /* Grab the object, r/w and annex. */
1991 if (decode_xfer (own_buf + 6, &object, &rw, &annex, &offset) < 0)
1993 write_enn (own_buf);
1994 return 1;
1997 for (i = 0;
1998 i < sizeof (qxfer_packets) / sizeof (qxfer_packets[0]);
1999 i++)
2001 const struct qxfer *q = &qxfer_packets[i];
2003 if (strcmp (object, q->object) == 0)
2005 if (strcmp (rw, "read") == 0)
2007 unsigned char *data;
2008 int n;
2009 CORE_ADDR ofs;
2010 unsigned int len;
2012 /* Grab the offset and length. */
2013 if (decode_xfer_read (offset, &ofs, &len) < 0)
2015 write_enn (own_buf);
2016 return 1;
2019 /* Read one extra byte, as an indicator of whether there is
2020 more. */
2021 if (len > PBUFSIZ - 2)
2022 len = PBUFSIZ - 2;
2023 data = (unsigned char *) malloc (len + 1);
2024 if (data == NULL)
2026 write_enn (own_buf);
2027 return 1;
2029 n = (*q->xfer) (annex, data, NULL, ofs, len + 1);
2030 if (n == -2)
2032 free (data);
2033 return 0;
2035 else if (n == -3)
2037 /* Preserve error message. */
2039 else if (n < 0)
2040 write_enn (own_buf);
2041 else if (n > len)
2042 *new_packet_len_p = write_qxfer_response (own_buf, data, len, 1);
2043 else
2044 *new_packet_len_p = write_qxfer_response (own_buf, data, n, 0);
2046 free (data);
2047 return 1;
2049 else if (strcmp (rw, "write") == 0)
2051 int n;
2052 unsigned int len;
2053 CORE_ADDR ofs;
2054 unsigned char *data;
2056 strcpy (own_buf, "E00");
2057 data = (unsigned char *) malloc (packet_len - (offset - own_buf));
2058 if (data == NULL)
2060 write_enn (own_buf);
2061 return 1;
2063 if (decode_xfer_write (offset, packet_len - (offset - own_buf),
2064 &ofs, &len, data) < 0)
2066 free (data);
2067 write_enn (own_buf);
2068 return 1;
2071 n = (*q->xfer) (annex, NULL, data, ofs, len);
2072 if (n == -2)
2074 free (data);
2075 return 0;
2077 else if (n == -3)
2079 /* Preserve error message. */
2081 else if (n < 0)
2082 write_enn (own_buf);
2083 else
2084 sprintf (own_buf, "%x", n);
2086 free (data);
2087 return 1;
2090 return 0;
2094 return 0;
2097 /* Compute 32 bit CRC from inferior memory.
2099 On success, return 32 bit CRC.
2100 On failure, return (unsigned long long) -1. */
2102 static unsigned long long
2103 crc32 (CORE_ADDR base, int len, unsigned int crc)
2105 while (len--)
2107 unsigned char byte = 0;
2109 /* Return failure if memory read fails. */
2110 if (read_inferior_memory (base, &byte, 1) != 0)
2111 return (unsigned long long) -1;
2113 crc = xcrc32 (&byte, 1, crc);
2114 base++;
2116 return (unsigned long long) crc;
2119 /* Parse the qMemTags packet request into ADDR and LEN. */
2121 static void
2122 parse_fetch_memtags_request (char *request, CORE_ADDR *addr, size_t *len,
2123 int *type)
2125 gdb_assert (startswith (request, "qMemTags:"));
2127 const char *p = request + strlen ("qMemTags:");
2129 /* Read address and length. */
2130 unsigned int length = 0;
2131 p = decode_m_packet_params (p, addr, &length, ':');
2132 *len = length;
2134 /* Read the tag type. */
2135 ULONGEST tag_type = 0;
2136 p = unpack_varlen_hex (p, &tag_type);
2137 *type = (int) tag_type;
2140 /* Add supported btrace packets to BUF. */
2142 static void
2143 supported_btrace_packets (char *buf)
2145 strcat (buf, ";Qbtrace:bts+");
2146 strcat (buf, ";Qbtrace-conf:bts:size+");
2147 strcat (buf, ";Qbtrace:pt+");
2148 strcat (buf, ";Qbtrace-conf:pt:size+");
2149 strcat (buf, ";Qbtrace:off+");
2150 strcat (buf, ";qXfer:btrace:read+");
2151 strcat (buf, ";qXfer:btrace-conf:read+");
2154 /* Handle all of the extended 'q' packets. */
2156 static void
2157 handle_query (char *own_buf, int packet_len, int *new_packet_len_p)
2159 client_state &cs = get_client_state ();
2160 static std::list<thread_info *>::const_iterator thread_iter;
2162 /* Reply the current thread id. */
2163 if (strcmp ("qC", own_buf) == 0 && !disable_packet_qC)
2165 ptid_t ptid;
2166 require_running_or_return (own_buf);
2168 if (cs.general_thread != null_ptid && cs.general_thread != minus_one_ptid)
2169 ptid = cs.general_thread;
2170 else
2172 thread_iter = all_threads.begin ();
2173 ptid = (*thread_iter)->id;
2176 sprintf (own_buf, "QC");
2177 own_buf += 2;
2178 write_ptid (own_buf, ptid);
2179 return;
2182 if (strcmp ("qSymbol::", own_buf) == 0)
2184 scoped_restore_current_thread restore_thread;
2186 /* For qSymbol, GDB only changes the current thread if the
2187 previous current thread was of a different process. So if
2188 the previous thread is gone, we need to pick another one of
2189 the same process. This can happen e.g., if we followed an
2190 exec in a non-leader thread. */
2191 if (current_thread == NULL)
2193 thread_info *any_thread
2194 = find_any_thread_of_pid (cs.general_thread.pid ());
2195 switch_to_thread (any_thread);
2197 /* Just in case, if we didn't find a thread, then bail out
2198 instead of crashing. */
2199 if (current_thread == NULL)
2201 write_enn (own_buf);
2202 return;
2206 /* GDB is suggesting new symbols have been loaded. This may
2207 mean a new shared library has been detected as loaded, so
2208 take the opportunity to check if breakpoints we think are
2209 inserted, still are. Note that it isn't guaranteed that
2210 we'll see this when a shared library is loaded, and nor will
2211 we see this for unloads (although breakpoints in unloaded
2212 libraries shouldn't trigger), as GDB may not find symbols for
2213 the library at all. We also re-validate breakpoints when we
2214 see a second GDB breakpoint for the same address, and or when
2215 we access breakpoint shadows. */
2216 validate_breakpoints ();
2218 if (target_supports_tracepoints ())
2219 tracepoint_look_up_symbols ();
2221 if (current_thread != NULL)
2222 the_target->look_up_symbols ();
2224 strcpy (own_buf, "OK");
2225 return;
2228 if (!disable_packet_qfThreadInfo)
2230 if (strcmp ("qfThreadInfo", own_buf) == 0)
2232 require_running_or_return (own_buf);
2233 thread_iter = all_threads.begin ();
2235 *own_buf++ = 'm';
2236 ptid_t ptid = (*thread_iter)->id;
2237 write_ptid (own_buf, ptid);
2238 thread_iter++;
2239 return;
2242 if (strcmp ("qsThreadInfo", own_buf) == 0)
2244 require_running_or_return (own_buf);
2245 if (thread_iter != all_threads.end ())
2247 *own_buf++ = 'm';
2248 ptid_t ptid = (*thread_iter)->id;
2249 write_ptid (own_buf, ptid);
2250 thread_iter++;
2251 return;
2253 else
2255 sprintf (own_buf, "l");
2256 return;
2261 if (the_target->supports_read_offsets ()
2262 && strcmp ("qOffsets", own_buf) == 0)
2264 CORE_ADDR text, data;
2266 require_running_or_return (own_buf);
2267 if (the_target->read_offsets (&text, &data))
2268 sprintf (own_buf, "Text=%lX;Data=%lX;Bss=%lX",
2269 (long)text, (long)data, (long)data);
2270 else
2271 write_enn (own_buf);
2273 return;
2276 /* Protocol features query. */
2277 if (startswith (own_buf, "qSupported")
2278 && (own_buf[10] == ':' || own_buf[10] == '\0'))
2280 char *p = &own_buf[10];
2281 int gdb_supports_qRelocInsn = 0;
2283 /* Process each feature being provided by GDB. The first
2284 feature will follow a ':', and latter features will follow
2285 ';'. */
2286 if (*p == ':')
2288 std::vector<std::string> qsupported;
2289 std::vector<const char *> unknowns;
2291 /* Two passes, to avoid nested strtok calls in
2292 target_process_qsupported. */
2293 char *saveptr;
2294 for (p = strtok_r (p + 1, ";", &saveptr);
2295 p != NULL;
2296 p = strtok_r (NULL, ";", &saveptr))
2297 qsupported.emplace_back (p);
2299 for (const std::string &feature : qsupported)
2301 if (feature == "multiprocess+")
2303 /* GDB supports and wants multi-process support if
2304 possible. */
2305 if (target_supports_multi_process ())
2306 cs.multi_process = 1;
2308 else if (feature == "qRelocInsn+")
2310 /* GDB supports relocate instruction requests. */
2311 gdb_supports_qRelocInsn = 1;
2313 else if (feature == "swbreak+")
2315 /* GDB wants us to report whether a trap is caused
2316 by a software breakpoint and for us to handle PC
2317 adjustment if necessary on this target. */
2318 if (target_supports_stopped_by_sw_breakpoint ())
2319 cs.swbreak_feature = 1;
2321 else if (feature == "hwbreak+")
2323 /* GDB wants us to report whether a trap is caused
2324 by a hardware breakpoint. */
2325 if (target_supports_stopped_by_hw_breakpoint ())
2326 cs.hwbreak_feature = 1;
2328 else if (feature == "fork-events+")
2330 /* GDB supports and wants fork events if possible. */
2331 if (target_supports_fork_events ())
2332 cs.report_fork_events = 1;
2334 else if (feature == "vfork-events+")
2336 /* GDB supports and wants vfork events if possible. */
2337 if (target_supports_vfork_events ())
2338 cs.report_vfork_events = 1;
2340 else if (feature == "exec-events+")
2342 /* GDB supports and wants exec events if possible. */
2343 if (target_supports_exec_events ())
2344 cs.report_exec_events = 1;
2346 else if (feature == "vContSupported+")
2347 cs.vCont_supported = 1;
2348 else if (feature == "QThreadEvents+")
2350 else if (feature == "no-resumed+")
2352 /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
2353 events. */
2354 report_no_resumed = true;
2356 else if (feature == "memory-tagging+")
2358 /* GDB supports memory tagging features. */
2359 if (target_supports_memory_tagging ())
2360 cs.memory_tagging_feature = true;
2362 else
2364 /* Move the unknown features all together. */
2365 unknowns.push_back (feature.c_str ());
2369 /* Give the target backend a chance to process the unknown
2370 features. */
2371 target_process_qsupported (unknowns);
2374 sprintf (own_buf,
2375 "PacketSize=%x;QPassSignals+;QProgramSignals+;"
2376 "QStartupWithShell+;QEnvironmentHexEncoded+;"
2377 "QEnvironmentReset+;QEnvironmentUnset+;"
2378 "QSetWorkingDir+",
2379 PBUFSIZ - 1);
2381 if (target_supports_catch_syscall ())
2382 strcat (own_buf, ";QCatchSyscalls+");
2384 if (the_target->supports_qxfer_libraries_svr4 ())
2385 strcat (own_buf, ";qXfer:libraries-svr4:read+"
2386 ";augmented-libraries-svr4-read+");
2387 else
2389 /* We do not have any hook to indicate whether the non-SVR4 target
2390 backend supports qXfer:libraries:read, so always report it. */
2391 strcat (own_buf, ";qXfer:libraries:read+");
2394 if (the_target->supports_read_auxv ())
2395 strcat (own_buf, ";qXfer:auxv:read+");
2397 if (the_target->supports_qxfer_siginfo ())
2398 strcat (own_buf, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2400 if (the_target->supports_read_loadmap ())
2401 strcat (own_buf, ";qXfer:fdpic:read+");
2403 /* We always report qXfer:features:read, as targets may
2404 install XML files on a subsequent call to arch_setup.
2405 If we reported to GDB on startup that we don't support
2406 qXfer:feature:read at all, we will never be re-queried. */
2407 strcat (own_buf, ";qXfer:features:read+");
2409 if (cs.transport_is_reliable)
2410 strcat (own_buf, ";QStartNoAckMode+");
2412 if (the_target->supports_qxfer_osdata ())
2413 strcat (own_buf, ";qXfer:osdata:read+");
2415 if (target_supports_multi_process ())
2416 strcat (own_buf, ";multiprocess+");
2418 if (target_supports_fork_events ())
2419 strcat (own_buf, ";fork-events+");
2421 if (target_supports_vfork_events ())
2422 strcat (own_buf, ";vfork-events+");
2424 if (target_supports_exec_events ())
2425 strcat (own_buf, ";exec-events+");
2427 if (target_supports_non_stop ())
2428 strcat (own_buf, ";QNonStop+");
2430 if (target_supports_disable_randomization ())
2431 strcat (own_buf, ";QDisableRandomization+");
2433 strcat (own_buf, ";qXfer:threads:read+");
2435 if (target_supports_tracepoints ())
2437 strcat (own_buf, ";ConditionalTracepoints+");
2438 strcat (own_buf, ";TraceStateVariables+");
2439 strcat (own_buf, ";TracepointSource+");
2440 strcat (own_buf, ";DisconnectedTracing+");
2441 if (gdb_supports_qRelocInsn && target_supports_fast_tracepoints ())
2442 strcat (own_buf, ";FastTracepoints+");
2443 strcat (own_buf, ";StaticTracepoints+");
2444 strcat (own_buf, ";InstallInTrace+");
2445 strcat (own_buf, ";qXfer:statictrace:read+");
2446 strcat (own_buf, ";qXfer:traceframe-info:read+");
2447 strcat (own_buf, ";EnableDisableTracepoints+");
2448 strcat (own_buf, ";QTBuffer:size+");
2449 strcat (own_buf, ";tracenz+");
2452 if (target_supports_hardware_single_step ()
2453 || target_supports_software_single_step () )
2455 strcat (own_buf, ";ConditionalBreakpoints+");
2457 strcat (own_buf, ";BreakpointCommands+");
2459 if (target_supports_agent ())
2460 strcat (own_buf, ";QAgent+");
2462 if (the_target->supports_btrace ())
2463 supported_btrace_packets (own_buf);
2465 if (target_supports_stopped_by_sw_breakpoint ())
2466 strcat (own_buf, ";swbreak+");
2468 if (target_supports_stopped_by_hw_breakpoint ())
2469 strcat (own_buf, ";hwbreak+");
2471 if (the_target->supports_pid_to_exec_file ())
2472 strcat (own_buf, ";qXfer:exec-file:read+");
2474 strcat (own_buf, ";vContSupported+");
2476 strcat (own_buf, ";QThreadEvents+");
2478 strcat (own_buf, ";no-resumed+");
2480 if (target_supports_memory_tagging ())
2481 strcat (own_buf, ";memory-tagging+");
2483 /* Reinitialize components as needed for the new connection. */
2484 hostio_handle_new_gdb_connection ();
2485 target_handle_new_gdb_connection ();
2487 return;
2490 /* Thread-local storage support. */
2491 if (the_target->supports_get_tls_address ()
2492 && startswith (own_buf, "qGetTLSAddr:"))
2494 char *p = own_buf + 12;
2495 CORE_ADDR parts[2], address = 0;
2496 int i, err;
2497 ptid_t ptid = null_ptid;
2499 require_running_or_return (own_buf);
2501 for (i = 0; i < 3; i++)
2503 char *p2;
2504 int len;
2506 if (p == NULL)
2507 break;
2509 p2 = strchr (p, ',');
2510 if (p2)
2512 len = p2 - p;
2513 p2++;
2515 else
2517 len = strlen (p);
2518 p2 = NULL;
2521 if (i == 0)
2522 ptid = read_ptid (p, NULL);
2523 else
2524 decode_address (&parts[i - 1], p, len);
2525 p = p2;
2528 if (p != NULL || i < 3)
2529 err = 1;
2530 else
2532 struct thread_info *thread = find_thread_ptid (ptid);
2534 if (thread == NULL)
2535 err = 2;
2536 else
2537 err = the_target->get_tls_address (thread, parts[0], parts[1],
2538 &address);
2541 if (err == 0)
2543 strcpy (own_buf, paddress(address));
2544 return;
2546 else if (err > 0)
2548 write_enn (own_buf);
2549 return;
2552 /* Otherwise, pretend we do not understand this packet. */
2555 /* Windows OS Thread Information Block address support. */
2556 if (the_target->supports_get_tib_address ()
2557 && startswith (own_buf, "qGetTIBAddr:"))
2559 const char *annex;
2560 int n;
2561 CORE_ADDR tlb;
2562 ptid_t ptid = read_ptid (own_buf + 12, &annex);
2564 n = the_target->get_tib_address (ptid, &tlb);
2565 if (n == 1)
2567 strcpy (own_buf, paddress(tlb));
2568 return;
2570 else if (n == 0)
2572 write_enn (own_buf);
2573 return;
2575 return;
2578 /* Handle "monitor" commands. */
2579 if (startswith (own_buf, "qRcmd,"))
2581 char *mon = (char *) malloc (PBUFSIZ);
2582 int len = strlen (own_buf + 6);
2584 if (mon == NULL)
2586 write_enn (own_buf);
2587 return;
2590 if ((len % 2) != 0
2591 || hex2bin (own_buf + 6, (gdb_byte *) mon, len / 2) != len / 2)
2593 write_enn (own_buf);
2594 free (mon);
2595 return;
2597 mon[len / 2] = '\0';
2599 write_ok (own_buf);
2601 if (the_target->handle_monitor_command (mon) == 0)
2602 /* Default processing. */
2603 handle_monitor_command (mon, own_buf);
2605 free (mon);
2606 return;
2609 if (startswith (own_buf, "qSearch:memory:"))
2611 require_running_or_return (own_buf);
2612 handle_search_memory (own_buf, packet_len);
2613 return;
2616 if (strcmp (own_buf, "qAttached") == 0
2617 || startswith (own_buf, "qAttached:"))
2619 struct process_info *process;
2621 if (own_buf[sizeof ("qAttached") - 1])
2623 int pid = strtoul (own_buf + sizeof ("qAttached:") - 1, NULL, 16);
2624 process = find_process_pid (pid);
2626 else
2628 require_running_or_return (own_buf);
2629 process = current_process ();
2632 if (process == NULL)
2634 write_enn (own_buf);
2635 return;
2638 strcpy (own_buf, process->attached ? "1" : "0");
2639 return;
2642 if (startswith (own_buf, "qCRC:"))
2644 /* CRC check (compare-section). */
2645 const char *comma;
2646 ULONGEST base;
2647 int len;
2648 unsigned long long crc;
2650 require_running_or_return (own_buf);
2651 comma = unpack_varlen_hex (own_buf + 5, &base);
2652 if (*comma++ != ',')
2654 write_enn (own_buf);
2655 return;
2657 len = strtoul (comma, NULL, 16);
2658 crc = crc32 (base, len, 0xffffffff);
2659 /* Check for memory failure. */
2660 if (crc == (unsigned long long) -1)
2662 write_enn (own_buf);
2663 return;
2665 sprintf (own_buf, "C%lx", (unsigned long) crc);
2666 return;
2669 if (handle_qxfer (own_buf, packet_len, new_packet_len_p))
2670 return;
2672 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf))
2673 return;
2675 /* Handle fetch memory tags packets. */
2676 if (startswith (own_buf, "qMemTags:")
2677 && target_supports_memory_tagging ())
2679 gdb::byte_vector tags;
2680 CORE_ADDR addr = 0;
2681 size_t len = 0;
2682 int type = 0;
2684 require_running_or_return (own_buf);
2686 parse_fetch_memtags_request (own_buf, &addr, &len, &type);
2688 bool ret = the_target->fetch_memtags (addr, len, tags, type);
2690 if (ret)
2691 ret = create_fetch_memtags_reply (own_buf, tags);
2693 if (!ret)
2694 write_enn (own_buf);
2696 *new_packet_len_p = strlen (own_buf);
2697 return;
2700 /* Otherwise we didn't know what packet it was. Say we didn't
2701 understand it. */
2702 own_buf[0] = 0;
2705 static void gdb_wants_all_threads_stopped (void);
2706 static void resume (struct thread_resume *actions, size_t n);
2708 /* The callback that is passed to visit_actioned_threads. */
2709 typedef int (visit_actioned_threads_callback_ftype)
2710 (const struct thread_resume *, struct thread_info *);
2712 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
2713 true if CALLBACK returns true. Returns false if no matching thread
2714 is found or CALLBACK results false.
2715 Note: This function is itself a callback for find_thread. */
2717 static bool
2718 visit_actioned_threads (thread_info *thread,
2719 const struct thread_resume *actions,
2720 size_t num_actions,
2721 visit_actioned_threads_callback_ftype *callback)
2723 for (size_t i = 0; i < num_actions; i++)
2725 const struct thread_resume *action = &actions[i];
2727 if (action->thread == minus_one_ptid
2728 || action->thread == thread->id
2729 || ((action->thread.pid ()
2730 == thread->id.pid ())
2731 && action->thread.lwp () == -1))
2733 if ((*callback) (action, thread))
2734 return true;
2738 return false;
2741 /* Callback for visit_actioned_threads. If the thread has a pending
2742 status to report, report it now. */
2744 static int
2745 handle_pending_status (const struct thread_resume *resumption,
2746 struct thread_info *thread)
2748 client_state &cs = get_client_state ();
2749 if (thread->status_pending_p)
2751 thread->status_pending_p = 0;
2753 cs.last_status = thread->last_status;
2754 cs.last_ptid = thread->id;
2755 prepare_resume_reply (cs.own_buf, cs.last_ptid, cs.last_status);
2756 return 1;
2758 return 0;
2761 /* Parse vCont packets. */
2762 static void
2763 handle_v_cont (char *own_buf)
2765 const char *p;
2766 int n = 0, i = 0;
2767 struct thread_resume *resume_info;
2768 struct thread_resume default_action { null_ptid };
2770 /* Count the number of semicolons in the packet. There should be one
2771 for every action. */
2772 p = &own_buf[5];
2773 while (p)
2775 n++;
2776 p++;
2777 p = strchr (p, ';');
2780 resume_info = (struct thread_resume *) malloc (n * sizeof (resume_info[0]));
2781 if (resume_info == NULL)
2782 goto err;
2784 p = &own_buf[5];
2785 while (*p)
2787 p++;
2789 memset (&resume_info[i], 0, sizeof resume_info[i]);
2791 if (p[0] == 's' || p[0] == 'S')
2792 resume_info[i].kind = resume_step;
2793 else if (p[0] == 'r')
2794 resume_info[i].kind = resume_step;
2795 else if (p[0] == 'c' || p[0] == 'C')
2796 resume_info[i].kind = resume_continue;
2797 else if (p[0] == 't')
2798 resume_info[i].kind = resume_stop;
2799 else
2800 goto err;
2802 if (p[0] == 'S' || p[0] == 'C')
2804 char *q;
2805 int sig = strtol (p + 1, &q, 16);
2806 if (p == q)
2807 goto err;
2808 p = q;
2810 if (!gdb_signal_to_host_p ((enum gdb_signal) sig))
2811 goto err;
2812 resume_info[i].sig = gdb_signal_to_host ((enum gdb_signal) sig);
2814 else if (p[0] == 'r')
2816 ULONGEST addr;
2818 p = unpack_varlen_hex (p + 1, &addr);
2819 resume_info[i].step_range_start = addr;
2821 if (*p != ',')
2822 goto err;
2824 p = unpack_varlen_hex (p + 1, &addr);
2825 resume_info[i].step_range_end = addr;
2827 else
2829 p = p + 1;
2832 if (p[0] == 0)
2834 resume_info[i].thread = minus_one_ptid;
2835 default_action = resume_info[i];
2837 /* Note: we don't increment i here, we'll overwrite this entry
2838 the next time through. */
2840 else if (p[0] == ':')
2842 const char *q;
2843 ptid_t ptid = read_ptid (p + 1, &q);
2845 if (p == q)
2846 goto err;
2847 p = q;
2848 if (p[0] != ';' && p[0] != 0)
2849 goto err;
2851 resume_info[i].thread = ptid;
2853 i++;
2857 if (i < n)
2858 resume_info[i] = default_action;
2860 resume (resume_info, n);
2861 free (resume_info);
2862 return;
2864 err:
2865 write_enn (own_buf);
2866 free (resume_info);
2867 return;
2870 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
2872 static void
2873 resume (struct thread_resume *actions, size_t num_actions)
2875 client_state &cs = get_client_state ();
2876 if (!non_stop)
2878 /* Check if among the threads that GDB wants actioned, there's
2879 one with a pending status to report. If so, skip actually
2880 resuming/stopping and report the pending event
2881 immediately. */
2883 thread_info *thread_with_status = find_thread ([&] (thread_info *thread)
2885 return visit_actioned_threads (thread, actions, num_actions,
2886 handle_pending_status);
2889 if (thread_with_status != NULL)
2890 return;
2892 enable_async_io ();
2895 the_target->resume (actions, num_actions);
2897 if (non_stop)
2898 write_ok (cs.own_buf);
2899 else
2901 cs.last_ptid = mywait (minus_one_ptid, &cs.last_status, 0, 1);
2903 if (cs.last_status.kind () == TARGET_WAITKIND_NO_RESUMED
2904 && !report_no_resumed)
2906 /* The client does not support this stop reply. At least
2907 return error. */
2908 sprintf (cs.own_buf, "E.No unwaited-for children left.");
2909 disable_async_io ();
2910 return;
2913 if (cs.last_status.kind () != TARGET_WAITKIND_EXITED
2914 && cs.last_status.kind () != TARGET_WAITKIND_SIGNALLED
2915 && cs.last_status.kind () != TARGET_WAITKIND_NO_RESUMED)
2916 current_thread->last_status = cs.last_status;
2918 /* From the client's perspective, all-stop mode always stops all
2919 threads implicitly (and the target backend has already done
2920 so by now). Tag all threads as "want-stopped", so we don't
2921 resume them implicitly without the client telling us to. */
2922 gdb_wants_all_threads_stopped ();
2923 prepare_resume_reply (cs.own_buf, cs.last_ptid, cs.last_status);
2924 disable_async_io ();
2926 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
2927 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
2928 target_mourn_inferior (cs.last_ptid);
2932 /* Attach to a new program. */
2933 static void
2934 handle_v_attach (char *own_buf)
2936 client_state &cs = get_client_state ();
2937 int pid;
2939 pid = strtol (own_buf + 8, NULL, 16);
2940 if (pid != 0 && attach_inferior (pid) == 0)
2942 /* Don't report shared library events after attaching, even if
2943 some libraries are preloaded. GDB will always poll the
2944 library list. Avoids the "stopped by shared library event"
2945 notice on the GDB side. */
2946 current_process ()->dlls_changed = false;
2948 if (non_stop)
2950 /* In non-stop, we don't send a resume reply. Stop events
2951 will follow up using the normal notification
2952 mechanism. */
2953 write_ok (own_buf);
2955 else
2956 prepare_resume_reply (own_buf, cs.last_ptid, cs.last_status);
2958 else
2959 write_enn (own_buf);
2962 /* Run a new program. */
2963 static void
2964 handle_v_run (char *own_buf)
2966 client_state &cs = get_client_state ();
2967 char *p, *next_p;
2968 std::vector<char *> new_argv;
2969 char *new_program_name = NULL;
2970 int i;
2972 for (i = 0, p = own_buf + strlen ("vRun;");
2973 /* Exit condition is at the end of the loop. */;
2974 p = next_p + 1, ++i)
2976 next_p = strchr (p, ';');
2977 if (next_p == NULL)
2978 next_p = p + strlen (p);
2980 if (i == 0 && p == next_p)
2982 /* No program specified. */
2983 new_program_name = NULL;
2985 else if (p == next_p)
2987 /* Empty argument. */
2988 new_argv.push_back (xstrdup (""));
2990 else
2992 /* The length of the decoded argument. */
2993 size_t len = (next_p - p) / 2;
2995 /* Buffer to decode the argument into. */
2996 char *arg = (char *) xmalloc (len + 1);
2998 hex2bin (p, (gdb_byte *) arg, len);
2999 arg[len] = '\0';
3001 if (i == 0)
3002 new_program_name = arg;
3003 else
3004 new_argv.push_back (arg);
3006 if (*next_p == '\0')
3007 break;
3010 if (new_program_name == NULL)
3012 /* GDB didn't specify a program to run. Use the program from the
3013 last run with the new argument list. */
3014 if (program_path.get () == NULL)
3016 write_enn (own_buf);
3017 free_vector_argv (new_argv);
3018 return;
3021 else
3022 program_path.set (new_program_name);
3024 /* Free the old argv and install the new one. */
3025 free_vector_argv (program_args);
3026 program_args = new_argv;
3028 target_create_inferior (program_path.get (), program_args);
3030 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
3032 prepare_resume_reply (own_buf, cs.last_ptid, cs.last_status);
3034 /* In non-stop, sending a resume reply doesn't set the general
3035 thread, but GDB assumes a vRun sets it (this is so GDB can
3036 query which is the main thread of the new inferior. */
3037 if (non_stop)
3038 cs.general_thread = cs.last_ptid;
3040 else
3041 write_enn (own_buf);
3044 /* Kill process. */
3045 static void
3046 handle_v_kill (char *own_buf)
3048 client_state &cs = get_client_state ();
3049 int pid;
3050 char *p = &own_buf[6];
3051 if (cs.multi_process)
3052 pid = strtol (p, NULL, 16);
3053 else
3054 pid = signal_pid;
3056 process_info *proc = find_process_pid (pid);
3058 if (proc != nullptr && kill_inferior (proc) == 0)
3060 cs.last_status.set_signalled (GDB_SIGNAL_KILL);
3061 cs.last_ptid = ptid_t (pid);
3062 discard_queued_stop_replies (cs.last_ptid);
3063 write_ok (own_buf);
3065 else
3066 write_enn (own_buf);
3069 /* Handle all of the extended 'v' packets. */
3070 void
3071 handle_v_requests (char *own_buf, int packet_len, int *new_packet_len)
3073 client_state &cs = get_client_state ();
3074 if (!disable_packet_vCont)
3076 if (strcmp (own_buf, "vCtrlC") == 0)
3078 the_target->request_interrupt ();
3079 write_ok (own_buf);
3080 return;
3083 if (startswith (own_buf, "vCont;"))
3085 handle_v_cont (own_buf);
3086 return;
3089 if (startswith (own_buf, "vCont?"))
3091 strcpy (own_buf, "vCont;c;C;t");
3093 if (target_supports_hardware_single_step ()
3094 || target_supports_software_single_step ()
3095 || !cs.vCont_supported)
3097 /* If target supports single step either by hardware or by
3098 software, add actions s and S to the list of supported
3099 actions. On the other hand, if GDB doesn't request the
3100 supported vCont actions in qSupported packet, add s and
3101 S to the list too. */
3102 own_buf = own_buf + strlen (own_buf);
3103 strcpy (own_buf, ";s;S");
3106 if (target_supports_range_stepping ())
3108 own_buf = own_buf + strlen (own_buf);
3109 strcpy (own_buf, ";r");
3111 return;
3115 if (startswith (own_buf, "vFile:")
3116 && handle_vFile (own_buf, packet_len, new_packet_len))
3117 return;
3119 if (startswith (own_buf, "vAttach;"))
3121 if ((!extended_protocol || !cs.multi_process) && target_running ())
3123 fprintf (stderr, "Already debugging a process\n");
3124 write_enn (own_buf);
3125 return;
3127 handle_v_attach (own_buf);
3128 return;
3131 if (startswith (own_buf, "vRun;"))
3133 if ((!extended_protocol || !cs.multi_process) && target_running ())
3135 fprintf (stderr, "Already debugging a process\n");
3136 write_enn (own_buf);
3137 return;
3139 handle_v_run (own_buf);
3140 return;
3143 if (startswith (own_buf, "vKill;"))
3145 if (!target_running ())
3147 fprintf (stderr, "No process to kill\n");
3148 write_enn (own_buf);
3149 return;
3151 handle_v_kill (own_buf);
3152 return;
3155 if (handle_notif_ack (own_buf, packet_len))
3156 return;
3158 /* Otherwise we didn't know what packet it was. Say we didn't
3159 understand it. */
3160 own_buf[0] = 0;
3161 return;
3164 /* Resume thread and wait for another event. In non-stop mode,
3165 don't really wait here, but return immediately to the event
3166 loop. */
3167 static void
3168 myresume (char *own_buf, int step, int sig)
3170 client_state &cs = get_client_state ();
3171 struct thread_resume resume_info[2];
3172 int n = 0;
3173 int valid_cont_thread;
3175 valid_cont_thread = (cs.cont_thread != null_ptid
3176 && cs.cont_thread != minus_one_ptid);
3178 if (step || sig || valid_cont_thread)
3180 resume_info[0].thread = current_ptid;
3181 if (step)
3182 resume_info[0].kind = resume_step;
3183 else
3184 resume_info[0].kind = resume_continue;
3185 resume_info[0].sig = sig;
3186 n++;
3189 if (!valid_cont_thread)
3191 resume_info[n].thread = minus_one_ptid;
3192 resume_info[n].kind = resume_continue;
3193 resume_info[n].sig = 0;
3194 n++;
3197 resume (resume_info, n);
3200 /* Callback for for_each_thread. Make a new stop reply for each
3201 stopped thread. */
3203 static void
3204 queue_stop_reply_callback (thread_info *thread)
3206 /* For now, assume targets that don't have this callback also don't
3207 manage the thread's last_status field. */
3208 if (!the_target->supports_thread_stopped ())
3210 struct vstop_notif *new_notif = new struct vstop_notif;
3212 new_notif->ptid = thread->id;
3213 new_notif->status = thread->last_status;
3214 /* Pass the last stop reply back to GDB, but don't notify
3215 yet. */
3216 notif_event_enque (&notif_stop, new_notif);
3218 else
3220 if (target_thread_stopped (thread))
3222 threads_debug_printf
3223 ("Reporting thread %s as already stopped with %s",
3224 target_pid_to_str (thread->id).c_str (),
3225 thread->last_status.to_string ().c_str ());
3227 gdb_assert (thread->last_status.kind () != TARGET_WAITKIND_IGNORE);
3229 /* Pass the last stop reply back to GDB, but don't notify
3230 yet. */
3231 queue_stop_reply (thread->id, thread->last_status);
3236 /* Set this inferior threads's state as "want-stopped". We won't
3237 resume this thread until the client gives us another action for
3238 it. */
3240 static void
3241 gdb_wants_thread_stopped (thread_info *thread)
3243 thread->last_resume_kind = resume_stop;
3245 if (thread->last_status.kind () == TARGET_WAITKIND_IGNORE)
3247 /* Most threads are stopped implicitly (all-stop); tag that with
3248 signal 0. */
3249 thread->last_status.set_stopped (GDB_SIGNAL_0);
3253 /* Set all threads' states as "want-stopped". */
3255 static void
3256 gdb_wants_all_threads_stopped (void)
3258 for_each_thread (gdb_wants_thread_stopped);
3261 /* Callback for for_each_thread. If the thread is stopped with an
3262 interesting event, mark it as having a pending event. */
3264 static void
3265 set_pending_status_callback (thread_info *thread)
3267 if (thread->last_status.kind () != TARGET_WAITKIND_STOPPED
3268 || (thread->last_status.sig () != GDB_SIGNAL_0
3269 /* A breakpoint, watchpoint or finished step from a previous
3270 GDB run isn't considered interesting for a new GDB run.
3271 If we left those pending, the new GDB could consider them
3272 random SIGTRAPs. This leaves out real async traps. We'd
3273 have to peek into the (target-specific) siginfo to
3274 distinguish those. */
3275 && thread->last_status.sig () != GDB_SIGNAL_TRAP))
3276 thread->status_pending_p = 1;
3279 /* Status handler for the '?' packet. */
3281 static void
3282 handle_status (char *own_buf)
3284 client_state &cs = get_client_state ();
3286 /* GDB is connected, don't forward events to the target anymore. */
3287 for_each_process ([] (process_info *process) {
3288 process->gdb_detached = 0;
3291 /* In non-stop mode, we must send a stop reply for each stopped
3292 thread. In all-stop mode, just send one for the first stopped
3293 thread we find. */
3295 if (non_stop)
3297 for_each_thread (queue_stop_reply_callback);
3299 /* The first is sent immediatly. OK is sent if there is no
3300 stopped thread, which is the same handling of the vStopped
3301 packet (by design). */
3302 notif_write_event (&notif_stop, cs.own_buf);
3304 else
3306 thread_info *thread = NULL;
3308 target_pause_all (false);
3309 target_stabilize_threads ();
3310 gdb_wants_all_threads_stopped ();
3312 /* We can only report one status, but we might be coming out of
3313 non-stop -- if more than one thread is stopped with
3314 interesting events, leave events for the threads we're not
3315 reporting now pending. They'll be reported the next time the
3316 threads are resumed. Start by marking all interesting events
3317 as pending. */
3318 for_each_thread (set_pending_status_callback);
3320 /* Prefer the last thread that reported an event to GDB (even if
3321 that was a GDB_SIGNAL_TRAP). */
3322 if (cs.last_status.kind () != TARGET_WAITKIND_IGNORE
3323 && cs.last_status.kind () != TARGET_WAITKIND_EXITED
3324 && cs.last_status.kind () != TARGET_WAITKIND_SIGNALLED)
3325 thread = find_thread_ptid (cs.last_ptid);
3327 /* If the last event thread is not found for some reason, look
3328 for some other thread that might have an event to report. */
3329 if (thread == NULL)
3330 thread = find_thread ([] (thread_info *thr_arg)
3332 return thr_arg->status_pending_p;
3335 /* If we're still out of luck, simply pick the first thread in
3336 the thread list. */
3337 if (thread == NULL)
3338 thread = get_first_thread ();
3340 if (thread != NULL)
3342 struct thread_info *tp = (struct thread_info *) thread;
3344 /* We're reporting this event, so it's no longer
3345 pending. */
3346 tp->status_pending_p = 0;
3348 /* GDB assumes the current thread is the thread we're
3349 reporting the status for. */
3350 cs.general_thread = thread->id;
3351 set_desired_thread ();
3353 gdb_assert (tp->last_status.kind () != TARGET_WAITKIND_IGNORE);
3354 prepare_resume_reply (own_buf, tp->id, tp->last_status);
3356 else
3357 strcpy (own_buf, "W00");
3361 static void
3362 gdbserver_version (void)
3364 printf ("GNU gdbserver %s%s\n"
3365 "Copyright (C) 2023 Free Software Foundation, Inc.\n"
3366 "gdbserver is free software, covered by the "
3367 "GNU General Public License.\n"
3368 "This gdbserver was configured as \"%s\"\n",
3369 PKGVERSION, version, host_name);
3372 static void
3373 gdbserver_usage (FILE *stream)
3375 fprintf (stream, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3376 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3377 "\tgdbserver [OPTIONS] --multi COMM\n"
3378 "\n"
3379 "COMM may either be a tty device (for serial debugging),\n"
3380 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3381 "stdin/stdout of gdbserver.\n"
3382 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3383 "PID is the process ID to attach to, when --attach is specified.\n"
3384 "\n"
3385 "Operating modes:\n"
3386 "\n"
3387 " --attach Attach to running process PID.\n"
3388 " --multi Start server without a specific program, and\n"
3389 " only quit when explicitly commanded.\n"
3390 " --once Exit after the first connection has closed.\n"
3391 " --help Print this message and then exit.\n"
3392 " --version Display version information and exit.\n"
3393 "\n"
3394 "Other options:\n"
3395 "\n"
3396 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3397 " --disable-randomization\n"
3398 " Run PROG with address space randomization disabled.\n"
3399 " --no-disable-randomization\n"
3400 " Don't disable address space randomization when\n"
3401 " starting PROG.\n"
3402 " --startup-with-shell\n"
3403 " Start PROG using a shell. I.e., execs a shell that\n"
3404 " then execs PROG. (default)\n"
3405 " --no-startup-with-shell\n"
3406 " Exec PROG directly instead of using a shell.\n"
3407 " Disables argument globbing and variable substitution\n"
3408 " on UNIX-like systems.\n"
3409 "\n"
3410 "Debug options:\n"
3411 "\n"
3412 " --debug Enable general debugging output.\n"
3413 " --debug-format=OPT1[,OPT2,...]\n"
3414 " Specify extra content in debugging output.\n"
3415 " Options:\n"
3416 " all\n"
3417 " none\n"
3418 " timestamp\n"
3419 " --remote-debug Enable remote protocol debugging output.\n"
3420 " --event-loop-debug Enable event loop debugging output.\n"
3421 " --disable-packet=OPT1[,OPT2,...]\n"
3422 " Disable support for RSP packets or features.\n"
3423 " Options:\n"
3424 " vCont, T, Tthread, qC, qfThreadInfo and \n"
3425 " threads (disable all threading packets).\n"
3426 "\n"
3427 "For more information, consult the GDB manual (available as on-line \n"
3428 "info or a printed manual).\n");
3429 if (REPORT_BUGS_TO[0] && stream == stdout)
3430 fprintf (stream, "Report bugs to \"%s\".\n", REPORT_BUGS_TO);
3433 static void
3434 gdbserver_show_disableable (FILE *stream)
3436 fprintf (stream, "Disableable packets:\n"
3437 " vCont \tAll vCont packets\n"
3438 " qC \tQuerying the current thread\n"
3439 " qfThreadInfo\tThread listing\n"
3440 " Tthread \tPassing the thread specifier in the "
3441 "T stop reply packet\n"
3442 " threads \tAll of the above\n"
3443 " T \tAll 'T' packets\n");
3446 /* Start up the event loop. This is the entry point to the event
3447 loop. */
3449 static void
3450 start_event_loop ()
3452 /* Loop until there is nothing to do. This is the entry point to
3453 the event loop engine. If nothing is ready at this time, wait
3454 for something to happen (via wait_for_event), then process it.
3455 Return when there are no longer event sources to wait for. */
3457 keep_processing_events = true;
3458 while (keep_processing_events)
3460 /* Any events already waiting in the queue? */
3461 int res = gdb_do_one_event ();
3463 /* Was there an error? */
3464 if (res == -1)
3465 break;
3468 /* We are done with the event loop. There are no more event sources
3469 to listen to. So we exit gdbserver. */
3472 static void
3473 kill_inferior_callback (process_info *process)
3475 kill_inferior (process);
3476 discard_queued_stop_replies (ptid_t (process->pid));
3479 /* Call this when exiting gdbserver with possible inferiors that need
3480 to be killed or detached from. */
3482 static void
3483 detach_or_kill_for_exit (void)
3485 /* First print a list of the inferiors we will be killing/detaching.
3486 This is to assist the user, for example, in case the inferior unexpectedly
3487 dies after we exit: did we screw up or did the inferior exit on its own?
3488 Having this info will save some head-scratching. */
3490 if (have_started_inferiors_p ())
3492 fprintf (stderr, "Killing process(es):");
3494 for_each_process ([] (process_info *process) {
3495 if (!process->attached)
3496 fprintf (stderr, " %d", process->pid);
3499 fprintf (stderr, "\n");
3501 if (have_attached_inferiors_p ())
3503 fprintf (stderr, "Detaching process(es):");
3505 for_each_process ([] (process_info *process) {
3506 if (process->attached)
3507 fprintf (stderr, " %d", process->pid);
3510 fprintf (stderr, "\n");
3513 /* Now we can kill or detach the inferiors. */
3514 for_each_process ([] (process_info *process) {
3515 int pid = process->pid;
3517 if (process->attached)
3518 detach_inferior (process);
3519 else
3520 kill_inferior (process);
3522 discard_queued_stop_replies (ptid_t (pid));
3526 /* Value that will be passed to exit(3) when gdbserver exits. */
3527 static int exit_code;
3529 /* Wrapper for detach_or_kill_for_exit that catches and prints
3530 errors. */
3532 static void
3533 detach_or_kill_for_exit_cleanup ()
3537 detach_or_kill_for_exit ();
3539 catch (const gdb_exception &exception)
3541 fflush (stdout);
3542 fprintf (stderr, "Detach or kill failed: %s\n",
3543 exception.what ());
3544 exit_code = 1;
3548 #if GDB_SELF_TEST
3550 namespace selftests {
3552 static void
3553 test_memory_tagging_functions (void)
3555 /* Setup testing. */
3556 gdb::char_vector packet;
3557 gdb::byte_vector tags, bv;
3558 std::string expected;
3559 packet.resize (32000);
3560 CORE_ADDR addr;
3561 size_t len;
3562 int type;
3564 /* Test parsing a qMemTags request. */
3566 /* Valid request, addr, len and type updated. */
3567 addr = 0xff;
3568 len = 255;
3569 type = 255;
3570 strcpy (packet.data (), "qMemTags:0,0:0");
3571 parse_fetch_memtags_request (packet.data (), &addr, &len, &type);
3572 SELF_CHECK (addr == 0 && len == 0 && type == 0);
3574 /* Valid request, addr, len and type updated. */
3575 addr = 0;
3576 len = 0;
3577 type = 0;
3578 strcpy (packet.data (), "qMemTags:deadbeef,ff:5");
3579 parse_fetch_memtags_request (packet.data (), &addr, &len, &type);
3580 SELF_CHECK (addr == 0xdeadbeef && len == 255 && type == 5);
3582 /* Test creating a qMemTags reply. */
3584 /* Non-empty tag data. */
3585 bv.resize (0);
3587 for (int i = 0; i < 5; i++)
3588 bv.push_back (i);
3590 expected = "m0001020304";
3591 SELF_CHECK (create_fetch_memtags_reply (packet.data (), bv) == true);
3592 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
3594 /* Test parsing a QMemTags request. */
3596 /* Valid request and empty tag data: addr, len, type and tags updated. */
3597 addr = 0xff;
3598 len = 255;
3599 type = 255;
3600 tags.resize (5);
3601 strcpy (packet.data (), "QMemTags:0,0:0:");
3602 SELF_CHECK (parse_store_memtags_request (packet.data (),
3603 &addr, &len, tags, &type) == true);
3604 SELF_CHECK (addr == 0 && len == 0 && type == 0 && tags.size () == 0);
3606 /* Valid request and non-empty tag data: addr, len, type
3607 and tags updated. */
3608 addr = 0;
3609 len = 0;
3610 type = 0;
3611 tags.resize (0);
3612 strcpy (packet.data (),
3613 "QMemTags:deadbeef,ff:5:0001020304");
3614 SELF_CHECK (parse_store_memtags_request (packet.data (), &addr, &len, tags,
3615 &type) == true);
3616 SELF_CHECK (addr == 0xdeadbeef && len == 255 && type == 5
3617 && tags.size () == 5);
3620 } // namespace selftests
3621 #endif /* GDB_SELF_TEST */
3623 /* Main function. This is called by the real "main" function,
3624 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
3626 static void ATTRIBUTE_NORETURN
3627 captured_main (int argc, char *argv[])
3629 int bad_attach;
3630 int pid;
3631 char *arg_end;
3632 const char *port = NULL;
3633 char **next_arg = &argv[1];
3634 volatile int multi_mode = 0;
3635 volatile int attach = 0;
3636 int was_running;
3637 bool selftest = false;
3638 #if GDB_SELF_TEST
3639 std::vector<const char *> selftest_filters;
3641 selftests::register_test ("remote_memory_tagging",
3642 selftests::test_memory_tagging_functions);
3643 #endif
3645 current_directory = getcwd (NULL, 0);
3646 client_state &cs = get_client_state ();
3648 if (current_directory == NULL)
3650 error (_("Could not find current working directory: %s"),
3651 safe_strerror (errno));
3654 while (*next_arg != NULL && **next_arg == '-')
3656 if (strcmp (*next_arg, "--version") == 0)
3658 gdbserver_version ();
3659 exit (0);
3661 else if (strcmp (*next_arg, "--help") == 0)
3663 gdbserver_usage (stdout);
3664 exit (0);
3666 else if (strcmp (*next_arg, "--attach") == 0)
3667 attach = 1;
3668 else if (strcmp (*next_arg, "--multi") == 0)
3669 multi_mode = 1;
3670 else if (strcmp (*next_arg, "--wrapper") == 0)
3672 char **tmp;
3674 next_arg++;
3676 tmp = next_arg;
3677 while (*next_arg != NULL && strcmp (*next_arg, "--") != 0)
3679 wrapper_argv += *next_arg;
3680 wrapper_argv += ' ';
3681 next_arg++;
3684 if (!wrapper_argv.empty ())
3686 /* Erase the last whitespace. */
3687 wrapper_argv.erase (wrapper_argv.end () - 1);
3690 if (next_arg == tmp || *next_arg == NULL)
3692 gdbserver_usage (stderr);
3693 exit (1);
3696 /* Consume the "--". */
3697 *next_arg = NULL;
3699 else if (strcmp (*next_arg, "--debug") == 0)
3700 debug_threads = true;
3701 else if (startswith (*next_arg, "--debug-format="))
3703 std::string error_msg
3704 = parse_debug_format_options ((*next_arg)
3705 + sizeof ("--debug-format=") - 1, 0);
3707 if (!error_msg.empty ())
3709 fprintf (stderr, "%s", error_msg.c_str ());
3710 exit (1);
3713 else if (strcmp (*next_arg, "--remote-debug") == 0)
3714 remote_debug = true;
3715 else if (strcmp (*next_arg, "--event-loop-debug") == 0)
3716 debug_event_loop = debug_event_loop_kind::ALL;
3717 else if (startswith (*next_arg, "--debug-file="))
3718 debug_set_output ((*next_arg) + sizeof ("--debug-file=") -1);
3719 else if (strcmp (*next_arg, "--disable-packet") == 0)
3721 gdbserver_show_disableable (stdout);
3722 exit (0);
3724 else if (startswith (*next_arg, "--disable-packet="))
3726 char *packets = *next_arg += sizeof ("--disable-packet=") - 1;
3727 char *saveptr;
3728 for (char *tok = strtok_r (packets, ",", &saveptr);
3729 tok != NULL;
3730 tok = strtok_r (NULL, ",", &saveptr))
3732 if (strcmp ("vCont", tok) == 0)
3733 disable_packet_vCont = true;
3734 else if (strcmp ("Tthread", tok) == 0)
3735 disable_packet_Tthread = true;
3736 else if (strcmp ("qC", tok) == 0)
3737 disable_packet_qC = true;
3738 else if (strcmp ("qfThreadInfo", tok) == 0)
3739 disable_packet_qfThreadInfo = true;
3740 else if (strcmp ("T", tok) == 0)
3741 disable_packet_T = true;
3742 else if (strcmp ("threads", tok) == 0)
3744 disable_packet_vCont = true;
3745 disable_packet_Tthread = true;
3746 disable_packet_qC = true;
3747 disable_packet_qfThreadInfo = true;
3749 else
3751 fprintf (stderr, "Don't know how to disable \"%s\".\n\n",
3752 tok);
3753 gdbserver_show_disableable (stderr);
3754 exit (1);
3758 else if (strcmp (*next_arg, "-") == 0)
3760 /* "-" specifies a stdio connection and is a form of port
3761 specification. */
3762 port = STDIO_CONNECTION_NAME;
3763 next_arg++;
3764 break;
3766 else if (strcmp (*next_arg, "--disable-randomization") == 0)
3767 cs.disable_randomization = 1;
3768 else if (strcmp (*next_arg, "--no-disable-randomization") == 0)
3769 cs.disable_randomization = 0;
3770 else if (strcmp (*next_arg, "--startup-with-shell") == 0)
3771 startup_with_shell = true;
3772 else if (strcmp (*next_arg, "--no-startup-with-shell") == 0)
3773 startup_with_shell = false;
3774 else if (strcmp (*next_arg, "--once") == 0)
3775 run_once = true;
3776 else if (strcmp (*next_arg, "--selftest") == 0)
3777 selftest = true;
3778 else if (startswith (*next_arg, "--selftest="))
3780 selftest = true;
3782 #if GDB_SELF_TEST
3783 const char *filter = *next_arg + strlen ("--selftest=");
3784 if (*filter == '\0')
3786 fprintf (stderr, _("Error: selftest filter is empty.\n"));
3787 exit (1);
3790 selftest_filters.push_back (filter);
3791 #endif
3793 else
3795 fprintf (stderr, "Unknown argument: %s\n", *next_arg);
3796 exit (1);
3799 next_arg++;
3800 continue;
3803 if (port == NULL)
3805 port = *next_arg;
3806 next_arg++;
3808 if ((port == NULL || (!attach && !multi_mode && *next_arg == NULL))
3809 && !selftest)
3811 gdbserver_usage (stderr);
3812 exit (1);
3815 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
3816 opened by remote_prepare. */
3817 notice_open_fds ();
3819 save_original_signals_state (false);
3821 /* We need to know whether the remote connection is stdio before
3822 starting the inferior. Inferiors created in this scenario have
3823 stdin,stdout redirected. So do this here before we call
3824 start_inferior. */
3825 if (port != NULL)
3826 remote_prepare (port);
3828 bad_attach = 0;
3829 pid = 0;
3831 /* --attach used to come after PORT, so allow it there for
3832 compatibility. */
3833 if (*next_arg != NULL && strcmp (*next_arg, "--attach") == 0)
3835 attach = 1;
3836 next_arg++;
3839 if (attach
3840 && (*next_arg == NULL
3841 || (*next_arg)[0] == '\0'
3842 || (pid = strtoul (*next_arg, &arg_end, 0)) == 0
3843 || *arg_end != '\0'
3844 || next_arg[1] != NULL))
3845 bad_attach = 1;
3847 if (bad_attach)
3849 gdbserver_usage (stderr);
3850 exit (1);
3853 /* Gather information about the environment. */
3854 our_environ = gdb_environ::from_host_environ ();
3856 initialize_async_io ();
3857 initialize_low ();
3858 have_job_control ();
3859 if (target_supports_tracepoints ())
3860 initialize_tracepoint ();
3862 mem_buf = (unsigned char *) xmalloc (PBUFSIZ);
3864 if (selftest)
3866 #if GDB_SELF_TEST
3867 selftests::run_tests (selftest_filters);
3868 #else
3869 printf (_("Selftests have been disabled for this build.\n"));
3870 #endif
3871 throw_quit ("Quit");
3874 if (pid == 0 && *next_arg != NULL)
3876 int i, n;
3878 n = argc - (next_arg - argv);
3879 program_path.set (next_arg[0]);
3880 for (i = 1; i < n; i++)
3881 program_args.push_back (xstrdup (next_arg[i]));
3883 /* Wait till we are at first instruction in program. */
3884 target_create_inferior (program_path.get (), program_args);
3886 /* We are now (hopefully) stopped at the first instruction of
3887 the target process. This assumes that the target process was
3888 successfully created. */
3890 else if (pid != 0)
3892 if (attach_inferior (pid) == -1)
3893 error ("Attaching not supported on this target");
3895 /* Otherwise succeeded. */
3897 else
3899 cs.last_status.set_exited (0);
3900 cs.last_ptid = minus_one_ptid;
3903 SCOPE_EXIT { detach_or_kill_for_exit_cleanup (); };
3905 /* Don't report shared library events on the initial connection,
3906 even if some libraries are preloaded. Avoids the "stopped by
3907 shared library event" notice on gdb side. */
3908 if (current_thread != nullptr)
3909 current_process ()->dlls_changed = false;
3911 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
3912 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
3913 was_running = 0;
3914 else
3915 was_running = 1;
3917 if (!was_running && !multi_mode)
3918 error ("No program to debug");
3920 while (1)
3922 cs.noack_mode = 0;
3923 cs.multi_process = 0;
3924 cs.report_fork_events = 0;
3925 cs.report_vfork_events = 0;
3926 cs.report_exec_events = 0;
3927 /* Be sure we're out of tfind mode. */
3928 cs.current_traceframe = -1;
3929 cs.cont_thread = null_ptid;
3930 cs.swbreak_feature = 0;
3931 cs.hwbreak_feature = 0;
3932 cs.vCont_supported = 0;
3933 cs.memory_tagging_feature = false;
3935 remote_open (port);
3939 /* Wait for events. This will return when all event sources
3940 are removed from the event loop. */
3941 start_event_loop ();
3943 /* If an exit was requested (using the "monitor exit"
3944 command), terminate now. */
3945 if (exit_requested)
3946 throw_quit ("Quit");
3948 /* The only other way to get here is for getpkt to fail:
3950 - If --once was specified, we're done.
3952 - If not in extended-remote mode, and we're no longer
3953 debugging anything, simply exit: GDB has disconnected
3954 after processing the last process exit.
3956 - Otherwise, close the connection and reopen it at the
3957 top of the loop. */
3958 if (run_once || (!extended_protocol && !target_running ()))
3959 throw_quit ("Quit");
3961 fprintf (stderr,
3962 "Remote side has terminated connection. "
3963 "GDBserver will reopen the connection.\n");
3965 /* Get rid of any pending statuses. An eventual reconnection
3966 (by the same GDB instance or another) will refresh all its
3967 state from scratch. */
3968 discard_queued_stop_replies (minus_one_ptid);
3969 for_each_thread ([] (thread_info *thread)
3971 thread->status_pending_p = 0;
3974 if (tracing)
3976 if (disconnected_tracing)
3978 /* Try to enable non-stop/async mode, so we we can
3979 both wait for an async socket accept, and handle
3980 async target events simultaneously. There's also
3981 no point either in having the target always stop
3982 all threads, when we're going to pass signals
3983 down without informing GDB. */
3984 if (!non_stop)
3986 if (the_target->start_non_stop (true))
3987 non_stop = 1;
3989 /* Detaching implicitly resumes all threads;
3990 simply disconnecting does not. */
3993 else
3995 fprintf (stderr,
3996 "Disconnected tracing disabled; "
3997 "stopping trace run.\n");
3998 stop_tracing ();
4002 catch (const gdb_exception_error &exception)
4004 fflush (stdout);
4005 fprintf (stderr, "gdbserver: %s\n", exception.what ());
4007 if (response_needed)
4009 write_enn (cs.own_buf);
4010 putpkt (cs.own_buf);
4013 if (run_once)
4014 throw_quit ("Quit");
4019 /* Main function. */
4022 main (int argc, char *argv[])
4027 captured_main (argc, argv);
4029 catch (const gdb_exception &exception)
4031 if (exception.reason == RETURN_ERROR)
4033 fflush (stdout);
4034 fprintf (stderr, "%s\n", exception.what ());
4035 fprintf (stderr, "Exiting\n");
4036 exit_code = 1;
4039 exit (exit_code);
4042 gdb_assert_not_reached ("captured_main should never return");
4045 /* Process options coming from Z packets for a breakpoint. PACKET is
4046 the packet buffer. *PACKET is updated to point to the first char
4047 after the last processed option. */
4049 static void
4050 process_point_options (struct gdb_breakpoint *bp, const char **packet)
4052 const char *dataptr = *packet;
4053 int persist;
4055 /* Check if data has the correct format. */
4056 if (*dataptr != ';')
4057 return;
4059 dataptr++;
4061 while (*dataptr)
4063 if (*dataptr == ';')
4064 ++dataptr;
4066 if (*dataptr == 'X')
4068 /* Conditional expression. */
4069 threads_debug_printf ("Found breakpoint condition.");
4070 if (!add_breakpoint_condition (bp, &dataptr))
4071 dataptr = strchrnul (dataptr, ';');
4073 else if (startswith (dataptr, "cmds:"))
4075 dataptr += strlen ("cmds:");
4076 threads_debug_printf ("Found breakpoint commands %s.", dataptr);
4077 persist = (*dataptr == '1');
4078 dataptr += 2;
4079 if (add_breakpoint_commands (bp, &dataptr, persist))
4080 dataptr = strchrnul (dataptr, ';');
4082 else
4084 fprintf (stderr, "Unknown token %c, ignoring.\n",
4085 *dataptr);
4086 /* Skip tokens until we find one that we recognize. */
4087 dataptr = strchrnul (dataptr, ';');
4090 *packet = dataptr;
4093 /* Event loop callback that handles a serial event. The first byte in
4094 the serial buffer gets us here. We expect characters to arrive at
4095 a brisk pace, so we read the rest of the packet with a blocking
4096 getpkt call. */
4098 static int
4099 process_serial_event (void)
4101 client_state &cs = get_client_state ();
4102 int signal;
4103 unsigned int len;
4104 CORE_ADDR mem_addr;
4105 unsigned char sig;
4106 int packet_len;
4107 int new_packet_len = -1;
4109 disable_async_io ();
4111 response_needed = false;
4112 packet_len = getpkt (cs.own_buf);
4113 if (packet_len <= 0)
4115 remote_close ();
4116 /* Force an event loop break. */
4117 return -1;
4119 response_needed = true;
4121 char ch = cs.own_buf[0];
4122 switch (ch)
4124 case 'q':
4125 handle_query (cs.own_buf, packet_len, &new_packet_len);
4126 break;
4127 case 'Q':
4128 handle_general_set (cs.own_buf);
4129 break;
4130 case 'D':
4131 handle_detach (cs.own_buf);
4132 break;
4133 case '!':
4134 extended_protocol = true;
4135 write_ok (cs.own_buf);
4136 break;
4137 case '?':
4138 handle_status (cs.own_buf);
4139 break;
4140 case 'H':
4141 if (cs.own_buf[1] == 'c' || cs.own_buf[1] == 'g' || cs.own_buf[1] == 's')
4143 require_running_or_break (cs.own_buf);
4145 ptid_t thread_id = read_ptid (&cs.own_buf[2], NULL);
4147 if (thread_id == null_ptid || thread_id == minus_one_ptid)
4148 thread_id = null_ptid;
4149 else if (thread_id.is_pid ())
4151 /* The ptid represents a pid. */
4152 thread_info *thread = find_any_thread_of_pid (thread_id.pid ());
4154 if (thread == NULL)
4156 write_enn (cs.own_buf);
4157 break;
4160 thread_id = thread->id;
4162 else
4164 /* The ptid represents a lwp/tid. */
4165 if (find_thread_ptid (thread_id) == NULL)
4167 write_enn (cs.own_buf);
4168 break;
4172 if (cs.own_buf[1] == 'g')
4174 if (thread_id == null_ptid)
4176 /* GDB is telling us to choose any thread. Check if
4177 the currently selected thread is still valid. If
4178 it is not, select the first available. */
4179 thread_info *thread = find_thread_ptid (cs.general_thread);
4180 if (thread == NULL)
4181 thread = get_first_thread ();
4182 thread_id = thread->id;
4185 cs.general_thread = thread_id;
4186 set_desired_thread ();
4187 gdb_assert (current_thread != NULL);
4189 else if (cs.own_buf[1] == 'c')
4190 cs.cont_thread = thread_id;
4192 write_ok (cs.own_buf);
4194 else
4196 /* Silently ignore it so that gdb can extend the protocol
4197 without compatibility headaches. */
4198 cs.own_buf[0] = '\0';
4200 break;
4201 case 'g':
4202 require_running_or_break (cs.own_buf);
4203 if (cs.current_traceframe >= 0)
4205 struct regcache *regcache
4206 = new_register_cache (current_target_desc ());
4208 if (fetch_traceframe_registers (cs.current_traceframe,
4209 regcache, -1) == 0)
4210 registers_to_string (regcache, cs.own_buf);
4211 else
4212 write_enn (cs.own_buf);
4213 free_register_cache (regcache);
4215 else
4217 struct regcache *regcache;
4219 if (!set_desired_thread ())
4220 write_enn (cs.own_buf);
4221 else
4223 regcache = get_thread_regcache (current_thread, 1);
4224 registers_to_string (regcache, cs.own_buf);
4227 break;
4228 case 'G':
4229 require_running_or_break (cs.own_buf);
4230 if (cs.current_traceframe >= 0)
4231 write_enn (cs.own_buf);
4232 else
4234 struct regcache *regcache;
4236 if (!set_desired_thread ())
4237 write_enn (cs.own_buf);
4238 else
4240 regcache = get_thread_regcache (current_thread, 1);
4241 registers_from_string (regcache, &cs.own_buf[1]);
4242 write_ok (cs.own_buf);
4245 break;
4246 case 'm':
4248 require_running_or_break (cs.own_buf);
4249 decode_m_packet (&cs.own_buf[1], &mem_addr, &len);
4250 int res = gdb_read_memory (mem_addr, mem_buf, len);
4251 if (res < 0)
4252 write_enn (cs.own_buf);
4253 else
4254 bin2hex (mem_buf, cs.own_buf, res);
4256 break;
4257 case 'M':
4258 require_running_or_break (cs.own_buf);
4259 decode_M_packet (&cs.own_buf[1], &mem_addr, &len, &mem_buf);
4260 if (gdb_write_memory (mem_addr, mem_buf, len) == 0)
4261 write_ok (cs.own_buf);
4262 else
4263 write_enn (cs.own_buf);
4264 break;
4265 case 'X':
4266 require_running_or_break (cs.own_buf);
4267 if (decode_X_packet (&cs.own_buf[1], packet_len - 1,
4268 &mem_addr, &len, &mem_buf) < 0
4269 || gdb_write_memory (mem_addr, mem_buf, len) != 0)
4270 write_enn (cs.own_buf);
4271 else
4272 write_ok (cs.own_buf);
4273 break;
4274 case 'C':
4275 require_running_or_break (cs.own_buf);
4276 hex2bin (cs.own_buf + 1, &sig, 1);
4277 if (gdb_signal_to_host_p ((enum gdb_signal) sig))
4278 signal = gdb_signal_to_host ((enum gdb_signal) sig);
4279 else
4280 signal = 0;
4281 myresume (cs.own_buf, 0, signal);
4282 break;
4283 case 'S':
4284 require_running_or_break (cs.own_buf);
4285 hex2bin (cs.own_buf + 1, &sig, 1);
4286 if (gdb_signal_to_host_p ((enum gdb_signal) sig))
4287 signal = gdb_signal_to_host ((enum gdb_signal) sig);
4288 else
4289 signal = 0;
4290 myresume (cs.own_buf, 1, signal);
4291 break;
4292 case 'c':
4293 require_running_or_break (cs.own_buf);
4294 signal = 0;
4295 myresume (cs.own_buf, 0, signal);
4296 break;
4297 case 's':
4298 require_running_or_break (cs.own_buf);
4299 signal = 0;
4300 myresume (cs.own_buf, 1, signal);
4301 break;
4302 case 'Z': /* insert_ ... */
4303 /* Fallthrough. */
4304 case 'z': /* remove_ ... */
4306 char *dataptr;
4307 ULONGEST addr;
4308 int kind;
4309 char type = cs.own_buf[1];
4310 int res;
4311 const int insert = ch == 'Z';
4312 const char *p = &cs.own_buf[3];
4314 p = unpack_varlen_hex (p, &addr);
4315 kind = strtol (p + 1, &dataptr, 16);
4317 if (insert)
4319 struct gdb_breakpoint *bp;
4321 bp = set_gdb_breakpoint (type, addr, kind, &res);
4322 if (bp != NULL)
4324 res = 0;
4326 /* GDB may have sent us a list of *point parameters to
4327 be evaluated on the target's side. Read such list
4328 here. If we already have a list of parameters, GDB
4329 is telling us to drop that list and use this one
4330 instead. */
4331 clear_breakpoint_conditions_and_commands (bp);
4332 const char *options = dataptr;
4333 process_point_options (bp, &options);
4336 else
4337 res = delete_gdb_breakpoint (type, addr, kind);
4339 if (res == 0)
4340 write_ok (cs.own_buf);
4341 else if (res == 1)
4342 /* Unsupported. */
4343 cs.own_buf[0] = '\0';
4344 else
4345 write_enn (cs.own_buf);
4346 break;
4348 case 'k':
4349 response_needed = false;
4350 if (!target_running ())
4351 /* The packet we received doesn't make sense - but we can't
4352 reply to it, either. */
4353 return 0;
4355 fprintf (stderr, "Killing all inferiors\n");
4357 for_each_process (kill_inferior_callback);
4359 /* When using the extended protocol, we wait with no program
4360 running. The traditional protocol will exit instead. */
4361 if (extended_protocol)
4363 cs.last_status.set_exited (GDB_SIGNAL_KILL);
4364 return 0;
4366 else
4367 exit (0);
4369 case 'T':
4371 require_running_or_break (cs.own_buf);
4373 ptid_t thread_id = read_ptid (&cs.own_buf[1], NULL);
4374 if (find_thread_ptid (thread_id) == NULL)
4376 write_enn (cs.own_buf);
4377 break;
4380 if (mythread_alive (thread_id))
4381 write_ok (cs.own_buf);
4382 else
4383 write_enn (cs.own_buf);
4385 break;
4386 case 'R':
4387 response_needed = false;
4389 /* Restarting the inferior is only supported in the extended
4390 protocol. */
4391 if (extended_protocol)
4393 if (target_running ())
4394 for_each_process (kill_inferior_callback);
4396 fprintf (stderr, "GDBserver restarting\n");
4398 /* Wait till we are at 1st instruction in prog. */
4399 if (program_path.get () != NULL)
4401 target_create_inferior (program_path.get (), program_args);
4403 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
4405 /* Stopped at the first instruction of the target
4406 process. */
4407 cs.general_thread = cs.last_ptid;
4409 else
4411 /* Something went wrong. */
4412 cs.general_thread = null_ptid;
4415 else
4417 cs.last_status.set_exited (GDB_SIGNAL_KILL);
4419 return 0;
4421 else
4423 /* It is a request we don't understand. Respond with an
4424 empty packet so that gdb knows that we don't support this
4425 request. */
4426 cs.own_buf[0] = '\0';
4427 break;
4429 case 'v':
4430 /* Extended (long) request. */
4431 handle_v_requests (cs.own_buf, packet_len, &new_packet_len);
4432 break;
4434 default:
4435 /* It is a request we don't understand. Respond with an empty
4436 packet so that gdb knows that we don't support this
4437 request. */
4438 cs.own_buf[0] = '\0';
4439 break;
4442 if (new_packet_len != -1)
4443 putpkt_binary (cs.own_buf, new_packet_len);
4444 else
4445 putpkt (cs.own_buf);
4447 response_needed = false;
4449 if (exit_requested)
4450 return -1;
4452 return 0;
4455 /* Event-loop callback for serial events. */
4457 void
4458 handle_serial_event (int err, gdb_client_data client_data)
4460 threads_debug_printf ("handling possible serial event");
4462 /* Really handle it. */
4463 if (process_serial_event () < 0)
4465 keep_processing_events = false;
4466 return;
4469 /* Be sure to not change the selected thread behind GDB's back.
4470 Important in the non-stop mode asynchronous protocol. */
4471 set_desired_thread ();
4474 /* Push a stop notification on the notification queue. */
4476 static void
4477 push_stop_notification (ptid_t ptid, const target_waitstatus &status)
4479 struct vstop_notif *vstop_notif = new struct vstop_notif;
4481 vstop_notif->status = status;
4482 vstop_notif->ptid = ptid;
4483 /* Push Stop notification. */
4484 notif_push (&notif_stop, vstop_notif);
4487 /* Event-loop callback for target events. */
4489 void
4490 handle_target_event (int err, gdb_client_data client_data)
4492 client_state &cs = get_client_state ();
4493 threads_debug_printf ("handling possible target event");
4495 cs.last_ptid = mywait (minus_one_ptid, &cs.last_status,
4496 TARGET_WNOHANG, 1);
4498 if (cs.last_status.kind () == TARGET_WAITKIND_NO_RESUMED)
4500 if (gdb_connected () && report_no_resumed)
4501 push_stop_notification (null_ptid, cs.last_status);
4503 else if (cs.last_status.kind () != TARGET_WAITKIND_IGNORE)
4505 int pid = cs.last_ptid.pid ();
4506 struct process_info *process = find_process_pid (pid);
4507 int forward_event = !gdb_connected () || process->gdb_detached;
4509 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
4510 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
4512 mark_breakpoints_out (process);
4513 target_mourn_inferior (cs.last_ptid);
4515 else if (cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED)
4517 else
4519 /* We're reporting this thread as stopped. Update its
4520 "want-stopped" state to what the client wants, until it
4521 gets a new resume action. */
4522 current_thread->last_resume_kind = resume_stop;
4523 current_thread->last_status = cs.last_status;
4526 if (forward_event)
4528 if (!target_running ())
4530 /* The last process exited. We're done. */
4531 exit (0);
4534 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
4535 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED
4536 || cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED)
4538 else
4540 /* A thread stopped with a signal, but gdb isn't
4541 connected to handle it. Pass it down to the
4542 inferior, as if it wasn't being traced. */
4543 enum gdb_signal signal;
4545 threads_debug_printf ("GDB not connected; forwarding event %d for"
4546 " [%s]",
4547 (int) cs.last_status.kind (),
4548 target_pid_to_str (cs.last_ptid).c_str ());
4550 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
4551 signal = cs.last_status.sig ();
4552 else
4553 signal = GDB_SIGNAL_0;
4554 target_continue (cs.last_ptid, signal);
4557 else
4558 push_stop_notification (cs.last_ptid, cs.last_status);
4561 /* Be sure to not change the selected thread behind GDB's back.
4562 Important in the non-stop mode asynchronous protocol. */
4563 set_desired_thread ();
4566 /* See gdbsupport/event-loop.h. */
4569 invoke_async_signal_handlers ()
4571 return 0;
4574 /* See gdbsupport/event-loop.h. */
4577 check_async_event_handlers ()
4579 return 0;
4582 /* See gdbsupport/errors.h */
4584 void
4585 flush_streams ()
4587 fflush (stdout);
4588 fflush (stderr);
4591 /* See gdbsupport/gdb_select.h. */
4594 gdb_select (int n, fd_set *readfds, fd_set *writefds,
4595 fd_set *exceptfds, struct timeval *timeout)
4597 return select (n, readfds, writefds, exceptfds, timeout);
4600 #if GDB_SELF_TEST
4601 namespace selftests
4604 void
4605 reset ()
4608 } // namespace selftests
4609 #endif /* GDB_SELF_TEST */