Add translations for various sub-directories
[binutils-gdb.git] / gdbserver / server.cc
blob0ad27d5e83006ffdde2682dd3f2183dbcb07c99c
1 /* Main code for remote server for GDB.
2 Copyright (C) 1989-2024 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 "gdbthread.h"
20 #include "gdbsupport/agent.h"
21 #include "notif.h"
22 #include "tdesc.h"
23 #include "gdbsupport/rsp-low.h"
24 #include "gdbsupport/signals-state-save-restore.h"
25 #include <ctype.h>
26 #include <unistd.h>
27 #if HAVE_SIGNAL_H
28 #include <signal.h>
29 #endif
30 #include "gdbsupport/gdb_vecs.h"
31 #include "gdbsupport/gdb_wait.h"
32 #include "gdbsupport/btrace-common.h"
33 #include "gdbsupport/filestuff.h"
34 #include "tracepoint.h"
35 #include "dll.h"
36 #include "hostio.h"
37 #include <vector>
38 #include <unordered_map>
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 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);
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;
125 /* All program arguments are merged into a single string. */
127 static std::string program_args;
129 static std::string wrapper_argv;
131 /* The PID of the originally created or attached inferior. Used to
132 send signals to the process when GDB sends us an asynchronous interrupt
133 (user hitting Control-C in the client), and to wait for the child to exit
134 when no longer debugging it. */
136 unsigned long signal_pid;
138 /* Set if you want to disable optional thread related packets support
139 in gdbserver, for the sake of testing GDB against stubs that don't
140 support them. */
141 bool disable_packet_vCont;
142 bool disable_packet_Tthread;
143 bool disable_packet_qC;
144 bool disable_packet_qfThreadInfo;
145 bool disable_packet_T;
147 static unsigned char *mem_buf;
149 /* A sub-class of 'struct notif_event' for stop, holding information
150 relative to a single stop reply. We keep a queue of these to
151 push to GDB in non-stop mode. */
153 struct vstop_notif : public notif_event
155 /* Thread or process that got the event. */
156 ptid_t ptid;
158 /* Event info. */
159 struct target_waitstatus status;
162 /* The current btrace configuration. This is gdbserver's mirror of GDB's
163 btrace configuration. */
164 static struct btrace_config current_btrace_conf;
166 /* The client remote protocol state. */
168 static client_state g_client_state;
170 client_state &
171 get_client_state ()
173 client_state &cs = g_client_state;
174 return cs;
178 /* Put a stop reply to the stop reply queue. */
180 static void
181 queue_stop_reply (ptid_t ptid, const target_waitstatus &status)
183 struct vstop_notif *new_notif = new struct vstop_notif;
185 new_notif->ptid = ptid;
186 new_notif->status = status;
188 notif_event_enque (&notif_stop, new_notif);
191 static bool
192 remove_all_on_match_ptid (struct notif_event *event, ptid_t filter_ptid)
194 struct vstop_notif *vstop_event = (struct vstop_notif *) event;
196 return vstop_event->ptid.matches (filter_ptid);
199 /* See server.h. */
201 void
202 discard_queued_stop_replies (ptid_t ptid)
204 std::list<notif_event *>::iterator iter, next, end;
205 end = notif_stop.queue.end ();
206 for (iter = notif_stop.queue.begin (); iter != end; iter = next)
208 next = iter;
209 ++next;
211 if (iter == notif_stop.queue.begin ())
213 /* The head of the list contains the notification that was
214 already sent to GDB. So we can't remove it, otherwise
215 when GDB sends the vStopped, it would ack the _next_
216 notification, which hadn't been sent yet! */
217 continue;
220 if (remove_all_on_match_ptid (*iter, ptid))
222 delete *iter;
223 notif_stop.queue.erase (iter);
228 static void
229 vstop_notif_reply (struct notif_event *event, char *own_buf)
231 struct vstop_notif *vstop = (struct vstop_notif *) event;
233 prepare_resume_reply (own_buf, vstop->ptid, vstop->status);
236 /* Helper for in_queued_stop_replies. */
238 static bool
239 in_queued_stop_replies_ptid (struct notif_event *event, ptid_t filter_ptid)
241 struct vstop_notif *vstop_event = (struct vstop_notif *) event;
243 if (vstop_event->ptid.matches (filter_ptid))
244 return true;
246 /* Don't resume fork children that GDB does not know about yet. */
247 if ((vstop_event->status.kind () == TARGET_WAITKIND_FORKED
248 || vstop_event->status.kind () == TARGET_WAITKIND_VFORKED
249 || vstop_event->status.kind () == TARGET_WAITKIND_THREAD_CLONED)
250 && vstop_event->status.child_ptid ().matches (filter_ptid))
251 return true;
253 return false;
256 /* See server.h. */
259 in_queued_stop_replies (ptid_t ptid)
261 for (notif_event *event : notif_stop.queue)
263 if (in_queued_stop_replies_ptid (event, ptid))
264 return true;
267 return false;
270 struct notif_server notif_stop =
272 "vStopped", "Stop", {}, vstop_notif_reply,
275 static int
276 target_running (void)
278 return get_first_thread () != NULL;
281 /* See gdbsupport/common-inferior.h. */
283 const char *
284 get_exec_wrapper ()
286 return !wrapper_argv.empty () ? wrapper_argv.c_str () : NULL;
289 /* See server.h. */
291 gdb_environ *
292 get_environ ()
294 return &our_environ;
297 static int
298 attach_inferior (int pid)
300 client_state &cs = get_client_state ();
301 /* myattach should return -1 if attaching is unsupported,
302 0 if it succeeded, and call error() otherwise. */
304 if (find_process_pid (pid) != nullptr)
305 error ("Already attached to process %d\n", pid);
307 if (myattach (pid) != 0)
308 return -1;
310 fprintf (stderr, "Attached; pid = %d\n", pid);
311 fflush (stderr);
313 /* FIXME - It may be that we should get the SIGNAL_PID from the
314 attach function, so that it can be the main thread instead of
315 whichever we were told to attach to. */
316 signal_pid = pid;
318 if (!non_stop)
320 cs.last_ptid = mywait (ptid_t (pid), &cs.last_status, 0, 0);
322 /* GDB knows to ignore the first SIGSTOP after attaching to a running
323 process using the "attach" command, but this is different; it's
324 just using "target remote". Pretend it's just starting up. */
325 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED
326 && cs.last_status.sig () == GDB_SIGNAL_STOP)
327 cs.last_status.set_stopped (GDB_SIGNAL_TRAP);
329 current_thread->last_resume_kind = resume_stop;
330 current_thread->last_status = cs.last_status;
333 return 0;
336 /* Decode a qXfer read request. Return 0 if everything looks OK,
337 or -1 otherwise. */
339 static int
340 decode_xfer_read (char *buf, CORE_ADDR *ofs, unsigned int *len)
342 /* After the read marker and annex, qXfer looks like a
343 traditional 'm' packet. */
344 decode_m_packet (buf, ofs, len);
346 return 0;
349 static int
350 decode_xfer (char *buf, char **object, char **rw, char **annex, char **offset)
352 /* Extract and NUL-terminate the object. */
353 *object = buf;
354 while (*buf && *buf != ':')
355 buf++;
356 if (*buf == '\0')
357 return -1;
358 *buf++ = 0;
360 /* Extract and NUL-terminate the read/write action. */
361 *rw = buf;
362 while (*buf && *buf != ':')
363 buf++;
364 if (*buf == '\0')
365 return -1;
366 *buf++ = 0;
368 /* Extract and NUL-terminate the annex. */
369 *annex = buf;
370 while (*buf && *buf != ':')
371 buf++;
372 if (*buf == '\0')
373 return -1;
374 *buf++ = 0;
376 *offset = buf;
377 return 0;
380 /* Write the response to a successful qXfer read. Returns the
381 length of the (binary) data stored in BUF, corresponding
382 to as much of DATA/LEN as we could fit. IS_MORE controls
383 the first character of the response. */
384 static int
385 write_qxfer_response (char *buf, const gdb_byte *data, int len, int is_more)
387 int out_len;
389 if (is_more)
390 buf[0] = 'm';
391 else
392 buf[0] = 'l';
394 return remote_escape_output (data, len, 1, (unsigned char *) buf + 1,
395 &out_len, PBUFSIZ - 2) + 1;
398 /* Handle btrace enabling in BTS format. */
400 static void
401 handle_btrace_enable_bts (thread_info *thread)
403 if (thread->btrace != NULL)
404 error (_("Btrace already enabled."));
406 current_btrace_conf.format = BTRACE_FORMAT_BTS;
407 thread->btrace = target_enable_btrace (thread, &current_btrace_conf);
410 /* Handle btrace enabling in Intel Processor Trace format. */
412 static void
413 handle_btrace_enable_pt (thread_info *thread)
415 if (thread->btrace != NULL)
416 error (_("Btrace already enabled."));
418 current_btrace_conf.format = BTRACE_FORMAT_PT;
419 thread->btrace = target_enable_btrace (thread, &current_btrace_conf);
422 /* Handle btrace disabling. */
424 static void
425 handle_btrace_disable (thread_info *thread)
428 if (thread->btrace == NULL)
429 error (_("Branch tracing not enabled."));
431 if (target_disable_btrace (thread->btrace) != 0)
432 error (_("Could not disable branch tracing."));
434 thread->btrace = NULL;
437 /* Handle the "Qbtrace" packet. */
439 static int
440 handle_btrace_general_set (char *own_buf)
442 client_state &cs = get_client_state ();
443 thread_info *thread;
444 char *op;
446 if (!startswith (own_buf, "Qbtrace:"))
447 return 0;
449 op = own_buf + strlen ("Qbtrace:");
451 if (cs.general_thread == null_ptid
452 || cs.general_thread == minus_one_ptid)
454 strcpy (own_buf, "E.Must select a single thread.");
455 return -1;
458 thread = find_thread_ptid (cs.general_thread);
459 if (thread == NULL)
461 strcpy (own_buf, "E.No such thread.");
462 return -1;
467 if (strcmp (op, "bts") == 0)
468 handle_btrace_enable_bts (thread);
469 else if (strcmp (op, "pt") == 0)
470 handle_btrace_enable_pt (thread);
471 else if (strcmp (op, "off") == 0)
472 handle_btrace_disable (thread);
473 else
474 error (_("Bad Qbtrace operation. Use bts, pt, or off."));
476 write_ok (own_buf);
478 catch (const gdb_exception_error &exception)
480 sprintf (own_buf, "E.%s", exception.what ());
483 return 1;
486 /* Handle the "Qbtrace-conf" packet. */
488 static int
489 handle_btrace_conf_general_set (char *own_buf)
491 client_state &cs = get_client_state ();
492 thread_info *thread;
493 char *op;
495 if (!startswith (own_buf, "Qbtrace-conf:"))
496 return 0;
498 op = own_buf + strlen ("Qbtrace-conf:");
500 if (cs.general_thread == null_ptid
501 || cs.general_thread == minus_one_ptid)
503 strcpy (own_buf, "E.Must select a single thread.");
504 return -1;
507 thread = find_thread_ptid (cs.general_thread);
508 if (thread == NULL)
510 strcpy (own_buf, "E.No such thread.");
511 return -1;
514 if (startswith (op, "bts:size="))
516 unsigned long size;
517 char *endp = NULL;
519 errno = 0;
520 size = strtoul (op + strlen ("bts:size="), &endp, 16);
521 if (endp == NULL || *endp != 0 || errno != 0 || size > UINT_MAX)
523 strcpy (own_buf, "E.Bad size value.");
524 return -1;
527 current_btrace_conf.bts.size = (unsigned int) size;
529 else if (strncmp (op, "pt:size=", strlen ("pt:size=")) == 0)
531 unsigned long size;
532 char *endp = NULL;
534 errno = 0;
535 size = strtoul (op + strlen ("pt:size="), &endp, 16);
536 if (endp == NULL || *endp != 0 || errno != 0 || size > UINT_MAX)
538 strcpy (own_buf, "E.Bad size value.");
539 return -1;
542 current_btrace_conf.pt.size = (unsigned int) size;
544 else if (strncmp (op, "pt:ptwrite=", strlen ("pt:ptwrite=")) == 0)
546 op += strlen ("pt:ptwrite=");
547 if (strncmp (op, "\"yes\"", strlen ("\"yes\"")) == 0)
548 current_btrace_conf.pt.ptwrite = true;
549 else if (strncmp (op, "\"no\"", strlen ("\"no\"")) == 0)
550 current_btrace_conf.pt.ptwrite = false;
551 else
553 strcpy (own_buf, "E.Bad ptwrite value.");
554 return -1;
557 else if (strncmp (op, "pt:event-tracing=", strlen ("pt:event-tracing=")) == 0)
559 op += strlen ("pt:event-tracing=");
560 if (strncmp (op, "\"yes\"", strlen ("\"yes\"")) == 0)
561 current_btrace_conf.pt.event_tracing = true;
562 else if (strncmp (op, "\"no\"", strlen ("\"no\"")) == 0)
563 current_btrace_conf.pt.event_tracing = false;
564 else
566 strcpy (own_buf, "E.Bad event-tracing value.");
567 return -1;
570 else
572 strcpy (own_buf, "E.Bad Qbtrace configuration option.");
573 return -1;
576 write_ok (own_buf);
577 return 1;
580 /* Create the qMemTags packet reply given TAGS.
582 Returns true if parsing succeeded and false otherwise. */
584 static bool
585 create_fetch_memtags_reply (char *reply, const gdb::byte_vector &tags)
587 /* It is an error to pass a zero-sized tag vector. */
588 gdb_assert (tags.size () != 0);
590 std::string packet ("m");
592 /* Write the tag data. */
593 packet += bin2hex (tags.data (), tags.size ());
595 /* Check if the reply is too big for the packet to handle. */
596 if (PBUFSIZ < packet.size ())
597 return false;
599 strcpy (reply, packet.c_str ());
600 return true;
603 /* Parse the QMemTags request into ADDR, LEN and TAGS.
605 Returns true if parsing succeeded and false otherwise. */
607 static bool
608 parse_store_memtags_request (char *request, CORE_ADDR *addr, size_t *len,
609 gdb::byte_vector &tags, int *type)
611 gdb_assert (startswith (request, "QMemTags:"));
613 const char *p = request + strlen ("QMemTags:");
615 /* Read address and length. */
616 unsigned int length = 0;
617 p = decode_m_packet_params (p, addr, &length, ':');
618 *len = length;
620 /* Read the tag type. */
621 ULONGEST tag_type = 0;
622 p = unpack_varlen_hex (p, &tag_type);
623 *type = (int) tag_type;
625 /* Make sure there is a colon after the type. */
626 if (*p != ':')
627 return false;
629 /* Skip the colon. */
630 p++;
632 /* Read the tag data. */
633 tags = hex2bin (p);
635 return true;
638 /* Parse thread options starting at *P and return them. On exit,
639 advance *P past the options. */
641 static gdb_thread_options
642 parse_gdb_thread_options (const char **p)
644 ULONGEST options = 0;
645 *p = unpack_varlen_hex (*p, &options);
646 return (gdb_thread_option) options;
649 /* Handle all of the extended 'Q' packets. */
651 static void
652 handle_general_set (char *own_buf)
654 client_state &cs = get_client_state ();
655 if (startswith (own_buf, "QPassSignals:"))
657 int numsigs = (int) GDB_SIGNAL_LAST, i;
658 const char *p = own_buf + strlen ("QPassSignals:");
659 CORE_ADDR cursig;
661 p = decode_address_to_semicolon (&cursig, p);
662 for (i = 0; i < numsigs; i++)
664 if (i == cursig)
666 cs.pass_signals[i] = 1;
667 if (*p == '\0')
668 /* Keep looping, to clear the remaining signals. */
669 cursig = -1;
670 else
671 p = decode_address_to_semicolon (&cursig, p);
673 else
674 cs.pass_signals[i] = 0;
676 strcpy (own_buf, "OK");
677 return;
680 if (startswith (own_buf, "QProgramSignals:"))
682 int numsigs = (int) GDB_SIGNAL_LAST, i;
683 const char *p = own_buf + strlen ("QProgramSignals:");
684 CORE_ADDR cursig;
686 cs.program_signals_p = 1;
688 p = decode_address_to_semicolon (&cursig, p);
689 for (i = 0; i < numsigs; i++)
691 if (i == cursig)
693 cs.program_signals[i] = 1;
694 if (*p == '\0')
695 /* Keep looping, to clear the remaining signals. */
696 cursig = -1;
697 else
698 p = decode_address_to_semicolon (&cursig, p);
700 else
701 cs.program_signals[i] = 0;
703 strcpy (own_buf, "OK");
704 return;
707 if (startswith (own_buf, "QCatchSyscalls:"))
709 const char *p = own_buf + sizeof ("QCatchSyscalls:") - 1;
710 int enabled = -1;
711 CORE_ADDR sysno;
712 struct process_info *process;
714 if (!target_running () || !target_supports_catch_syscall ())
716 write_enn (own_buf);
717 return;
720 if (strcmp (p, "0") == 0)
721 enabled = 0;
722 else if (p[0] == '1' && (p[1] == ';' || p[1] == '\0'))
723 enabled = 1;
724 else
726 fprintf (stderr, "Unknown catch-syscalls mode requested: %s\n",
727 own_buf);
728 write_enn (own_buf);
729 return;
732 process = current_process ();
733 process->syscalls_to_catch.clear ();
735 if (enabled)
737 p += 1;
738 if (*p == ';')
740 p += 1;
741 while (*p != '\0')
743 p = decode_address_to_semicolon (&sysno, p);
744 process->syscalls_to_catch.push_back (sysno);
747 else
748 process->syscalls_to_catch.push_back (ANY_SYSCALL);
751 write_ok (own_buf);
752 return;
755 if (strcmp (own_buf, "QEnvironmentReset") == 0)
757 our_environ = gdb_environ::from_host_environ ();
759 write_ok (own_buf);
760 return;
763 if (startswith (own_buf, "QEnvironmentHexEncoded:"))
765 const char *p = own_buf + sizeof ("QEnvironmentHexEncoded:") - 1;
766 /* The final form of the environment variable. FINAL_VAR will
767 hold the 'VAR=VALUE' format. */
768 std::string final_var = hex2str (p);
769 std::string var_name, var_value;
771 remote_debug_printf ("[QEnvironmentHexEncoded received '%s']", p);
772 remote_debug_printf ("[Environment variable to be set: '%s']",
773 final_var.c_str ());
775 size_t pos = final_var.find ('=');
776 if (pos == std::string::npos)
778 warning (_("Unexpected format for environment variable: '%s'"),
779 final_var.c_str ());
780 write_enn (own_buf);
781 return;
784 var_name = final_var.substr (0, pos);
785 var_value = final_var.substr (pos + 1, std::string::npos);
787 our_environ.set (var_name.c_str (), var_value.c_str ());
789 write_ok (own_buf);
790 return;
793 if (startswith (own_buf, "QEnvironmentUnset:"))
795 const char *p = own_buf + sizeof ("QEnvironmentUnset:") - 1;
796 std::string varname = hex2str (p);
798 remote_debug_printf ("[QEnvironmentUnset received '%s']", p);
799 remote_debug_printf ("[Environment variable to be unset: '%s']",
800 varname.c_str ());
802 our_environ.unset (varname.c_str ());
804 write_ok (own_buf);
805 return;
808 if (strcmp (own_buf, "QStartNoAckMode") == 0)
810 remote_debug_printf ("[noack mode enabled]");
812 cs.noack_mode = 1;
813 write_ok (own_buf);
814 return;
817 if (startswith (own_buf, "QNonStop:"))
819 char *mode = own_buf + 9;
820 int req = -1;
821 const char *req_str;
823 if (strcmp (mode, "0") == 0)
824 req = 0;
825 else if (strcmp (mode, "1") == 0)
826 req = 1;
827 else
829 /* We don't know what this mode is, so complain to
830 GDB. */
831 fprintf (stderr, "Unknown non-stop mode requested: %s\n",
832 own_buf);
833 write_enn (own_buf);
834 return;
837 req_str = req ? "non-stop" : "all-stop";
838 if (the_target->start_non_stop (req == 1) != 0)
840 fprintf (stderr, "Setting %s mode failed\n", req_str);
841 write_enn (own_buf);
842 return;
845 non_stop = (req != 0);
847 remote_debug_printf ("[%s mode enabled]", req_str);
849 write_ok (own_buf);
850 return;
853 if (startswith (own_buf, "QDisableRandomization:"))
855 char *packet = own_buf + strlen ("QDisableRandomization:");
856 ULONGEST setting;
858 unpack_varlen_hex (packet, &setting);
859 cs.disable_randomization = setting;
861 remote_debug_printf (cs.disable_randomization
862 ? "[address space randomization disabled]"
863 : "[address space randomization enabled]");
865 write_ok (own_buf);
866 return;
869 if (target_supports_tracepoints ()
870 && handle_tracepoint_general_set (own_buf))
871 return;
873 if (startswith (own_buf, "QAgent:"))
875 char *mode = own_buf + strlen ("QAgent:");
876 int req = 0;
878 if (strcmp (mode, "0") == 0)
879 req = 0;
880 else if (strcmp (mode, "1") == 0)
881 req = 1;
882 else
884 /* We don't know what this value is, so complain to GDB. */
885 sprintf (own_buf, "E.Unknown QAgent value");
886 return;
889 /* Update the flag. */
890 use_agent = req;
891 remote_debug_printf ("[%s agent]", req ? "Enable" : "Disable");
892 write_ok (own_buf);
893 return;
896 if (handle_btrace_general_set (own_buf))
897 return;
899 if (handle_btrace_conf_general_set (own_buf))
900 return;
902 if (startswith (own_buf, "QThreadEvents:"))
904 char *mode = own_buf + strlen ("QThreadEvents:");
905 enum tribool req = TRIBOOL_UNKNOWN;
907 if (strcmp (mode, "0") == 0)
908 req = TRIBOOL_FALSE;
909 else if (strcmp (mode, "1") == 0)
910 req = TRIBOOL_TRUE;
911 else
913 /* We don't know what this mode is, so complain to GDB. */
914 std::string err
915 = string_printf ("E.Unknown thread-events mode requested: %s\n",
916 mode);
917 strcpy (own_buf, err.c_str ());
918 return;
921 cs.report_thread_events = (req == TRIBOOL_TRUE);
923 remote_debug_printf ("[thread events are now %s]\n",
924 cs.report_thread_events ? "enabled" : "disabled");
926 write_ok (own_buf);
927 return;
930 if (startswith (own_buf, "QThreadOptions;"))
932 const char *p = own_buf + strlen ("QThreadOptions");
934 gdb_thread_options supported_options = target_supported_thread_options ();
935 if (supported_options == 0)
937 /* Something went wrong -- we don't support any option, but
938 GDB sent the packet anyway. */
939 write_enn (own_buf);
940 return;
943 /* We could store the options directly in thread->thread_options
944 without this map, but that would mean that a QThreadOptions
945 packet with a wildcard like "QThreadOptions;0;3:TID" would
946 result in the debug logs showing:
948 [options for TID are now 0x0]
949 [options for TID are now 0x3]
951 It's nicer if we only print the final options for each TID,
952 and if we only print about it if the options changed compared
953 to the options that were previously set on the thread. */
954 std::unordered_map<thread_info *, gdb_thread_options> set_options;
956 while (*p != '\0')
958 if (p[0] != ';')
960 write_enn (own_buf);
961 return;
963 p++;
965 /* Read the options. */
967 gdb_thread_options options = parse_gdb_thread_options (&p);
969 if ((options & ~supported_options) != 0)
971 /* GDB asked for an unknown or unsupported option, so
972 error out. */
973 std::string err
974 = string_printf ("E.Unknown thread options requested: %s\n",
975 to_string (options).c_str ());
976 strcpy (own_buf, err.c_str ());
977 return;
980 ptid_t ptid;
982 if (p[0] == ';' || p[0] == '\0')
983 ptid = minus_one_ptid;
984 else if (p[0] == ':')
986 const char *q;
988 ptid = read_ptid (p + 1, &q);
990 if (p == q)
992 write_enn (own_buf);
993 return;
995 p = q;
996 if (p[0] != ';' && p[0] != '\0')
998 write_enn (own_buf);
999 return;
1002 else
1004 write_enn (own_buf);
1005 return;
1008 /* Convert PID.-1 => PID.0 for ptid.matches. */
1009 if (ptid.lwp () == -1)
1010 ptid = ptid_t (ptid.pid ());
1012 for_each_thread ([&] (thread_info *thread)
1014 if (thread->id.matches (ptid))
1015 set_options[thread] = options;
1019 for (const auto &iter : set_options)
1021 thread_info *thread = iter.first;
1022 gdb_thread_options options = iter.second;
1024 if (thread->thread_options != options)
1026 threads_debug_printf ("[options for %s are now %s]\n",
1027 target_pid_to_str (thread->id).c_str (),
1028 to_string (options).c_str ());
1030 thread->thread_options = options;
1034 write_ok (own_buf);
1035 return;
1038 if (startswith (own_buf, "QStartupWithShell:"))
1040 const char *value = own_buf + strlen ("QStartupWithShell:");
1042 if (strcmp (value, "1") == 0)
1043 startup_with_shell = true;
1044 else if (strcmp (value, "0") == 0)
1045 startup_with_shell = false;
1046 else
1048 /* Unknown value. */
1049 fprintf (stderr, "Unknown value to startup-with-shell: %s\n",
1050 own_buf);
1051 write_enn (own_buf);
1052 return;
1055 remote_debug_printf ("[Inferior will %s started with shell]",
1056 startup_with_shell ? "be" : "not be");
1058 write_ok (own_buf);
1059 return;
1062 if (startswith (own_buf, "QSetWorkingDir:"))
1064 const char *p = own_buf + strlen ("QSetWorkingDir:");
1066 if (*p != '\0')
1068 std::string path = hex2str (p);
1070 remote_debug_printf ("[Set the inferior's current directory to %s]",
1071 path.c_str ());
1073 set_inferior_cwd (std::move (path));
1075 else
1077 /* An empty argument means that we should clear out any
1078 previously set cwd for the inferior. */
1079 set_inferior_cwd ("");
1081 remote_debug_printf ("[Unset the inferior's current directory; will "
1082 "use gdbserver's cwd]");
1084 write_ok (own_buf);
1086 return;
1090 /* Handle store memory tags packets. */
1091 if (startswith (own_buf, "QMemTags:")
1092 && target_supports_memory_tagging ())
1094 gdb::byte_vector tags;
1095 CORE_ADDR addr = 0;
1096 size_t len = 0;
1097 int type = 0;
1099 require_running_or_return (own_buf);
1101 bool ret = parse_store_memtags_request (own_buf, &addr, &len, tags,
1102 &type);
1104 if (ret)
1105 ret = the_target->store_memtags (addr, len, tags, type);
1107 if (!ret)
1108 write_enn (own_buf);
1109 else
1110 write_ok (own_buf);
1112 return;
1115 /* Otherwise we didn't know what packet it was. Say we didn't
1116 understand it. */
1117 own_buf[0] = 0;
1120 static const char *
1121 get_features_xml (const char *annex)
1123 const struct target_desc *desc = current_target_desc ();
1125 /* `desc->xmltarget' defines what to return when looking for the
1126 "target.xml" file. Its contents can either be verbatim XML code
1127 (prefixed with a '@') or else the name of the actual XML file to
1128 be used in place of "target.xml".
1130 This variable is set up from the auto-generated
1131 init_registers_... routine for the current target. */
1133 if (strcmp (annex, "target.xml") == 0)
1135 const char *ret = tdesc_get_features_xml (desc);
1137 if (*ret == '@')
1138 return ret + 1;
1139 else
1140 annex = ret;
1143 #ifdef USE_XML
1145 int i;
1147 /* Look for the annex. */
1148 for (i = 0; xml_builtin[i][0] != NULL; i++)
1149 if (strcmp (annex, xml_builtin[i][0]) == 0)
1150 break;
1152 if (xml_builtin[i][0] != NULL)
1153 return xml_builtin[i][1];
1155 #endif
1157 return NULL;
1160 static void
1161 monitor_show_help (void)
1163 monitor_output ("The following monitor commands are supported:\n");
1164 monitor_output (" set debug on\n");
1165 monitor_output (" Enable general debugging messages\n");
1166 monitor_output (" set debug off\n");
1167 monitor_output (" Disable all debugging messages\n");
1168 monitor_output (" set debug COMPONENT <off|on>\n");
1169 monitor_output (" Enable debugging messages for COMPONENT, which is\n");
1170 monitor_output (" one of: all, threads, remote, event-loop.\n");
1171 monitor_output (" set debug-hw-points <0|1>\n");
1172 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
1173 monitor_output (" set debug-format option1[,option2,...]\n");
1174 monitor_output (" Add additional information to debugging messages\n");
1175 monitor_output (" Options: all, none, timestamp\n");
1176 monitor_output (" exit\n");
1177 monitor_output (" Quit GDBserver\n");
1180 /* Read trace frame or inferior memory. Returns the number of bytes
1181 actually read, zero when no further transfer is possible, and -1 on
1182 error. Return of a positive value smaller than LEN does not
1183 indicate there's no more to be read, only the end of the transfer.
1184 E.g., when GDB reads memory from a traceframe, a first request may
1185 be served from a memory block that does not cover the whole request
1186 length. A following request gets the rest served from either
1187 another block (of the same traceframe) or from the read-only
1188 regions. */
1190 static int
1191 gdb_read_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
1193 client_state &cs = get_client_state ();
1194 int res;
1196 if (cs.current_traceframe >= 0)
1198 ULONGEST nbytes;
1199 ULONGEST length = len;
1201 if (traceframe_read_mem (cs.current_traceframe,
1202 memaddr, myaddr, len, &nbytes))
1203 return -1;
1204 /* Data read from trace buffer, we're done. */
1205 if (nbytes > 0)
1206 return nbytes;
1207 if (!in_readonly_region (memaddr, length))
1208 return -1;
1209 /* Otherwise we have a valid readonly case, fall through. */
1210 /* (assume no half-trace half-real blocks for now) */
1213 if (set_desired_process ())
1214 res = read_inferior_memory (memaddr, myaddr, len);
1215 else
1216 res = 1;
1218 return res == 0 ? len : -1;
1221 /* Write trace frame or inferior memory. Actually, writing to trace
1222 frames is forbidden. */
1224 static int
1225 gdb_write_memory (CORE_ADDR memaddr, const unsigned char *myaddr, int len)
1227 client_state &cs = get_client_state ();
1228 if (cs.current_traceframe >= 0)
1229 return EIO;
1230 else
1232 int ret;
1234 if (set_desired_process ())
1235 ret = target_write_memory (memaddr, myaddr, len);
1236 else
1237 ret = EIO;
1238 return ret;
1242 /* Handle qSearch:memory packets. */
1244 static void
1245 handle_search_memory (char *own_buf, int packet_len)
1247 CORE_ADDR start_addr;
1248 CORE_ADDR search_space_len;
1249 gdb_byte *pattern;
1250 unsigned int pattern_len;
1251 int found;
1252 CORE_ADDR found_addr;
1253 int cmd_name_len = sizeof ("qSearch:memory:") - 1;
1255 pattern = (gdb_byte *) malloc (packet_len);
1256 if (pattern == NULL)
1257 error ("Unable to allocate memory to perform the search");
1259 if (decode_search_memory_packet (own_buf + cmd_name_len,
1260 packet_len - cmd_name_len,
1261 &start_addr, &search_space_len,
1262 pattern, &pattern_len) < 0)
1264 free (pattern);
1265 error ("Error in parsing qSearch:memory packet");
1268 auto read_memory = [] (CORE_ADDR addr, gdb_byte *result, size_t len)
1270 return gdb_read_memory (addr, result, len) == len;
1273 found = simple_search_memory (read_memory, start_addr, search_space_len,
1274 pattern, pattern_len, &found_addr);
1276 if (found > 0)
1277 sprintf (own_buf, "1,%lx", (long) found_addr);
1278 else if (found == 0)
1279 strcpy (own_buf, "0");
1280 else
1281 strcpy (own_buf, "E00");
1283 free (pattern);
1286 /* Handle the "D" packet. */
1288 static void
1289 handle_detach (char *own_buf)
1291 client_state &cs = get_client_state ();
1293 process_info *process;
1295 if (cs.multi_process)
1297 /* skip 'D;' */
1298 int pid = strtol (&own_buf[2], NULL, 16);
1300 process = find_process_pid (pid);
1302 else
1303 process = current_process ();
1305 if (process == NULL)
1307 write_enn (own_buf);
1308 return;
1311 if ((tracing && disconnected_tracing) || any_persistent_commands (process))
1313 if (tracing && disconnected_tracing)
1314 fprintf (stderr,
1315 "Disconnected tracing in effect, "
1316 "leaving gdbserver attached to the process\n");
1318 if (any_persistent_commands (process))
1319 fprintf (stderr,
1320 "Persistent commands are present, "
1321 "leaving gdbserver attached to the process\n");
1323 /* Make sure we're in non-stop/async mode, so we we can both
1324 wait for an async socket accept, and handle async target
1325 events simultaneously. There's also no point either in
1326 having the target stop all threads, when we're going to
1327 pass signals down without informing GDB. */
1328 if (!non_stop)
1330 threads_debug_printf ("Forcing non-stop mode");
1332 non_stop = true;
1333 the_target->start_non_stop (true);
1336 process->gdb_detached = 1;
1338 /* Detaching implicitly resumes all threads. */
1339 target_continue_no_signal (minus_one_ptid);
1341 write_ok (own_buf);
1342 return;
1345 fprintf (stderr, "Detaching from process %d\n", process->pid);
1346 stop_tracing ();
1348 /* We'll need this after PROCESS has been destroyed. */
1349 int pid = process->pid;
1351 /* If this process has an unreported fork child, that child is not known to
1352 GDB, so GDB won't take care of detaching it. We must do it here.
1354 Here, we specifically don't want to use "safe iteration", as detaching
1355 another process might delete the next thread in the iteration, which is
1356 the one saved by the safe iterator. We will never delete the currently
1357 iterated on thread, so standard iteration should be safe. */
1358 for (thread_info &thread : process->thread_list ())
1360 /* Only threads that have a pending fork event. */
1361 target_waitkind kind;
1362 thread_info *child = target_thread_pending_child (&thread, &kind);
1363 if (child == nullptr || kind == TARGET_WAITKIND_THREAD_CLONED)
1364 continue;
1366 process_info *fork_child_process = child->process ();
1367 int fork_child_pid = fork_child_process->pid;
1369 if (detach_inferior (fork_child_process) != 0)
1370 warning (_("Failed to detach fork child %s, child of %s"),
1371 target_pid_to_str (ptid_t (fork_child_pid)).c_str (),
1372 target_pid_to_str (thread.id).c_str ());
1375 if (detach_inferior (process) != 0)
1376 write_enn (own_buf);
1377 else
1379 discard_queued_stop_replies (ptid_t (pid));
1380 write_ok (own_buf);
1382 if (extended_protocol || target_running ())
1384 /* There is still at least one inferior remaining or
1385 we are in extended mode, so don't terminate gdbserver,
1386 and instead treat this like a normal program exit. */
1387 cs.last_status.set_exited (0);
1388 cs.last_ptid = ptid_t (pid);
1390 switch_to_thread (nullptr);
1392 else
1394 putpkt (own_buf);
1395 remote_close ();
1397 /* If we are attached, then we can exit. Otherwise, we
1398 need to hang around doing nothing, until the child is
1399 gone. */
1400 join_inferior (pid);
1401 exit (0);
1406 /* Parse options to --debug-format= and "monitor set debug-format".
1407 ARG is the text after "--debug-format=" or "monitor set debug-format".
1408 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1409 This triggers calls to monitor_output.
1410 The result is an empty string if all options were parsed ok, otherwise an
1411 error message which the caller must free.
1413 N.B. These commands affect all debug format settings, they are not
1414 cumulative. If a format is not specified, it is turned off.
1415 However, we don't go to extra trouble with things like
1416 "monitor set debug-format all,none,timestamp".
1417 Instead we just parse them one at a time, in order.
1419 The syntax for "monitor set debug" we support here is not identical
1420 to gdb's "set debug foo on|off" because we also use this function to
1421 parse "--debug-format=foo,bar". */
1423 static std::string
1424 parse_debug_format_options (const char *arg, int is_monitor)
1426 /* First turn all debug format options off. */
1427 debug_timestamp = 0;
1429 /* First remove leading spaces, for "monitor set debug-format". */
1430 while (isspace (*arg))
1431 ++arg;
1433 std::vector<gdb::unique_xmalloc_ptr<char>> options
1434 = delim_string_to_char_ptr_vec (arg, ',');
1436 for (const gdb::unique_xmalloc_ptr<char> &option : options)
1438 if (strcmp (option.get (), "all") == 0)
1440 debug_timestamp = 1;
1441 if (is_monitor)
1442 monitor_output ("All extra debug format options enabled.\n");
1444 else if (strcmp (option.get (), "none") == 0)
1446 debug_timestamp = 0;
1447 if (is_monitor)
1448 monitor_output ("All extra debug format options disabled.\n");
1450 else if (strcmp (option.get (), "timestamp") == 0)
1452 debug_timestamp = 1;
1453 if (is_monitor)
1454 monitor_output ("Timestamps will be added to debug output.\n");
1456 else if (*option == '\0')
1458 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1459 continue;
1461 else
1462 return string_printf ("Unknown debug-format argument: \"%s\"\n",
1463 option.get ());
1466 return std::string ();
1469 /* A wrapper to enable, or disable a debug flag. These are debug flags
1470 that control the debug output from gdbserver, that developers might
1471 want, this is not something most end users will need. */
1473 struct debug_opt
1475 /* NAME is the name of this debug option, this should be a simple string
1476 containing no whitespace, starting with a letter from isalpha(), and
1477 contain only isalnum() characters and '_' underscore and '-' hyphen.
1479 SETTER is a callback function used to set the debug variable. This
1480 callback will be passed true to enable the debug setting, or false to
1481 disable the debug setting. */
1482 debug_opt (const char *name, std::function<void (bool)> setter)
1483 : m_name (name),
1484 m_setter (setter)
1486 gdb_assert (isalpha (*name));
1489 /* Called to enable or disable the debug setting. */
1490 void set (bool enable) const
1492 m_setter (enable);
1495 /* Return the name of this debug option. */
1496 const char *name () const
1497 { return m_name; }
1499 private:
1500 /* The name of this debug option. */
1501 const char *m_name;
1503 /* The callback to update the debug setting. */
1504 std::function<void (bool)> m_setter;
1507 /* The set of all debug options that gdbserver supports. These are the
1508 options that can be passed to the command line '--debug=...' flag, or to
1509 the monitor command 'monitor set debug ...'. */
1511 static std::vector<debug_opt> all_debug_opt {
1512 {"threads", [] (bool enable)
1514 debug_threads = enable;
1516 {"remote", [] (bool enable)
1518 remote_debug = enable;
1520 {"event-loop", [] (bool enable)
1522 debug_event_loop = (enable ? debug_event_loop_kind::ALL
1523 : debug_event_loop_kind::OFF);
1527 /* Parse the options to --debug=...
1529 OPTIONS is the string of debug components which should be enabled (or
1530 disabled), and must not be nullptr. An empty OPTIONS string is valid,
1531 in which case a default set of debug components will be enabled.
1533 An unknown, or otherwise invalid debug component will result in an
1534 exception being thrown.
1536 OPTIONS can consist of multiple debug component names separated by a
1537 comma. Debugging for each component will be turned on. The special
1538 component 'all' can be used to enable debugging for all components.
1540 A component can also be prefixed with '-' to disable debugging of that
1541 component, so a user might use: '--debug=all,-remote', to enable all
1542 debugging, except for the remote (protocol) component. Components are
1543 processed left to write in the OPTIONS list. */
1545 static void
1546 parse_debug_options (const char *options)
1548 gdb_assert (options != nullptr);
1550 /* Empty options means the "default" set. This exists mostly for
1551 backwards compatibility with gdbserver's legacy behavior. */
1552 if (*options == '\0')
1553 options = "+threads";
1555 while (*options != '\0')
1557 const char *end = strchrnul (options, ',');
1559 bool enable = *options != '-';
1560 if (*options == '-' || *options == '+')
1561 ++options;
1563 std::string opt (options, end - options);
1565 if (opt.size () == 0)
1566 error ("invalid empty debug option");
1568 bool is_opt_all = opt == "all";
1570 bool found = false;
1571 for (const auto &debug_opt : all_debug_opt)
1572 if (is_opt_all || opt == debug_opt.name ())
1574 debug_opt.set (enable);
1575 found = true;
1576 if (!is_opt_all)
1577 break;
1580 if (!found)
1581 error ("unknown debug option '%s'", opt.c_str ());
1583 options = (*end == ',') ? end + 1 : end;
1587 /* Called from the 'monitor' command handler, to handle general 'set debug'
1588 monitor commands with one of the formats:
1590 set debug COMPONENT VALUE
1591 set debug VALUE
1593 In both of these command formats VALUE can be 'on', 'off', '1', or '0'
1594 with 1/0 being equivalent to on/off respectively.
1596 In the no-COMPONENT version of the command, if VALUE is 'on' (or '1')
1597 then the component 'threads' is assumed, this is for backward
1598 compatibility, but maybe in the future we might find a better "default"
1599 set of debug flags to enable.
1601 In the no-COMPONENT version of the command, if VALUE is 'off' (or '0')
1602 then all debugging is turned off.
1604 Otherwise, COMPONENT must be one of the known debug components, and that
1605 component is either enabled or disabled as appropriate.
1607 The string MON contains either 'COMPONENT VALUE' or just the 'VALUE' for
1608 the second command format, the 'set debug ' has been stripped off
1609 already.
1611 Return a string containing an error message if something goes wrong,
1612 this error can be returned as part of the monitor command output. If
1613 everything goes correctly then the debug global will have been updated,
1614 and an empty string is returned. */
1616 static std::string
1617 handle_general_monitor_debug (const char *mon)
1619 mon = skip_spaces (mon);
1621 if (*mon == '\0')
1622 return "No debug component name found.\n";
1624 /* Find the first word within MON. This is either the component name,
1625 or the value if no component has been given. */
1626 const char *end = skip_to_space (mon);
1627 std::string component (mon, end - mon);
1628 if (component.find (',') != component.npos || component[0] == '-'
1629 || component[0] == '+')
1630 return "Invalid character found in debug component name.\n";
1632 /* In ACTION_STR we create a string that will be passed to the
1633 parse_debug_options string. This will be either '+COMPONENT' or
1634 '-COMPONENT' depending on whether we want to enable or disable
1635 COMPONENT. */
1636 std::string action_str;
1638 /* If parse_debug_options succeeds, then MSG will be returned to the user
1639 as the output of the monitor command. */
1640 std::string msg;
1642 /* Check for 'set debug off', this disables all debug output. */
1643 if (component == "0" || component == "off")
1645 if (*skip_spaces (end) != '\0')
1646 return string_printf
1647 ("Junk '%s' found at end of 'set debug %s' command.\n",
1648 skip_spaces (end), std::string (mon, end - mon).c_str ());
1650 action_str = "-all";
1651 msg = "All debug output disabled.\n";
1653 /* Check for 'set debug on', this disables a general set of debug. */
1654 else if (component == "1" || component == "on")
1656 if (*skip_spaces (end) != '\0')
1657 return string_printf
1658 ("Junk '%s' found at end of 'set debug %s' command.\n",
1659 skip_spaces (end), std::string (mon, end - mon).c_str ());
1661 action_str = "+threads";
1662 msg = "General debug output enabled.\n";
1664 /* Otherwise we should have 'set debug COMPONENT VALUE'. Extract the two
1665 parts and validate. */
1666 else
1668 /* Figure out the value the user passed. */
1669 const char *value_start = skip_spaces (end);
1670 if (*value_start == '\0')
1671 return string_printf ("Missing value for 'set debug %s' command.\n",
1672 mon);
1674 const char *after_value = skip_to_space (value_start);
1675 if (*skip_spaces (after_value) != '\0')
1676 return string_printf
1677 ("Junk '%s' found at end of 'set debug %s' command.\n",
1678 skip_spaces (after_value),
1679 std::string (mon, after_value - mon).c_str ());
1681 std::string value (value_start, after_value - value_start);
1683 /* Check VALUE to see if we are enabling, or disabling. */
1684 bool enable;
1685 if (value == "0" || value == "off")
1686 enable = false;
1687 else if (value == "1" || value == "on")
1688 enable = true;
1689 else
1690 return string_printf ("Invalid value '%s' for 'set debug %s'.\n",
1691 value.c_str (),
1692 std::string (mon, end - mon).c_str ());
1694 action_str = std::string (enable ? "+" : "-") + component;
1695 msg = string_printf ("Debug output for '%s' %s.\n", component.c_str (),
1696 enable ? "enabled" : "disabled");
1699 gdb_assert (!msg.empty ());
1700 gdb_assert (!action_str.empty ());
1704 parse_debug_options (action_str.c_str ());
1705 monitor_output (msg.c_str ());
1707 catch (const gdb_exception_error &exception)
1709 return string_printf ("Error: %s\n", exception.what ());
1712 return {};
1715 /* Handle monitor commands not handled by target-specific handlers. */
1717 static void
1718 handle_monitor_command (char *mon, char *own_buf)
1720 if (startswith (mon, "set debug "))
1722 std::string error_msg
1723 = handle_general_monitor_debug (mon + sizeof ("set debug ") - 1);
1725 if (!error_msg.empty ())
1727 monitor_output (error_msg.c_str ());
1728 monitor_show_help ();
1729 write_enn (own_buf);
1732 else if (strcmp (mon, "set debug-hw-points 1") == 0)
1734 show_debug_regs = 1;
1735 monitor_output ("H/W point debugging output enabled.\n");
1737 else if (strcmp (mon, "set debug-hw-points 0") == 0)
1739 show_debug_regs = 0;
1740 monitor_output ("H/W point debugging output disabled.\n");
1742 else if (startswith (mon, "set debug-format "))
1744 std::string error_msg
1745 = parse_debug_format_options (mon + sizeof ("set debug-format ") - 1,
1748 if (!error_msg.empty ())
1750 monitor_output (error_msg.c_str ());
1751 monitor_show_help ();
1752 write_enn (own_buf);
1755 else if (strcmp (mon, "set debug-file") == 0)
1756 debug_set_output (nullptr);
1757 else if (startswith (mon, "set debug-file "))
1758 debug_set_output (mon + sizeof ("set debug-file ") - 1);
1759 else if (strcmp (mon, "help") == 0)
1760 monitor_show_help ();
1761 else if (strcmp (mon, "exit") == 0)
1762 exit_requested = true;
1763 else
1765 monitor_output ("Unknown monitor command.\n\n");
1766 monitor_show_help ();
1767 write_enn (own_buf);
1771 /* Associates a callback with each supported qXfer'able object. */
1773 struct qxfer
1775 /* The object this handler handles. */
1776 const char *object;
1778 /* Request that the target transfer up to LEN 8-bit bytes of the
1779 target's OBJECT. The OFFSET, for a seekable object, specifies
1780 the starting point. The ANNEX can be used to provide additional
1781 data-specific information to the target.
1783 Return the number of bytes actually transferred, zero when no
1784 further transfer is possible, -1 on error, -2 when the transfer
1785 is not supported, and -3 on a verbose error message that should
1786 be preserved. Return of a positive value smaller than LEN does
1787 not indicate the end of the object, only the end of the transfer.
1789 One, and only one, of readbuf or writebuf must be non-NULL. */
1790 int (*xfer) (const char *annex,
1791 gdb_byte *readbuf, const gdb_byte *writebuf,
1792 ULONGEST offset, LONGEST len);
1795 /* Handle qXfer:auxv:read. */
1797 static int
1798 handle_qxfer_auxv (const char *annex,
1799 gdb_byte *readbuf, const gdb_byte *writebuf,
1800 ULONGEST offset, LONGEST len)
1802 if (!the_target->supports_read_auxv () || writebuf != NULL)
1803 return -2;
1805 if (annex[0] != '\0' || current_thread == NULL)
1806 return -1;
1808 return the_target->read_auxv (current_thread->id.pid (), offset, readbuf,
1809 len);
1812 /* Handle qXfer:exec-file:read. */
1814 static int
1815 handle_qxfer_exec_file (const char *annex,
1816 gdb_byte *readbuf, const gdb_byte *writebuf,
1817 ULONGEST offset, LONGEST len)
1819 ULONGEST pid;
1820 int total_len;
1822 if (!the_target->supports_pid_to_exec_file () || writebuf != NULL)
1823 return -2;
1825 if (annex[0] == '\0')
1827 if (current_thread == NULL)
1828 return -1;
1830 pid = current_thread->id.pid ();
1832 else
1834 annex = unpack_varlen_hex (annex, &pid);
1835 if (annex[0] != '\0')
1836 return -1;
1839 if (pid <= 0)
1840 return -1;
1842 const char *file = the_target->pid_to_exec_file (pid);
1843 if (file == NULL)
1844 return -1;
1846 total_len = strlen (file);
1848 if (offset > total_len)
1849 return -1;
1851 if (offset + len > total_len)
1852 len = total_len - offset;
1854 memcpy (readbuf, file + offset, len);
1855 return len;
1858 /* Handle qXfer:features:read. */
1860 static int
1861 handle_qxfer_features (const char *annex,
1862 gdb_byte *readbuf, const gdb_byte *writebuf,
1863 ULONGEST offset, LONGEST len)
1865 const char *document;
1866 size_t total_len;
1868 if (writebuf != NULL)
1869 return -2;
1871 if (!target_running ())
1872 return -1;
1874 /* Grab the correct annex. */
1875 document = get_features_xml (annex);
1876 if (document == NULL)
1877 return -1;
1879 total_len = strlen (document);
1881 if (offset > total_len)
1882 return -1;
1884 if (offset + len > total_len)
1885 len = total_len - offset;
1887 memcpy (readbuf, document + offset, len);
1888 return len;
1891 /* Handle qXfer:libraries:read. */
1893 static int
1894 handle_qxfer_libraries (const char *annex,
1895 gdb_byte *readbuf, const gdb_byte *writebuf,
1896 ULONGEST offset, LONGEST len)
1898 if (writebuf != NULL)
1899 return -2;
1901 if (annex[0] != '\0' || current_thread == NULL)
1902 return -1;
1904 std::string document = "<library-list version=\"1.0\">\n";
1906 process_info *proc = current_process ();
1907 for (const dll_info &dll : proc->all_dlls)
1908 document += string_printf
1909 (" <library name=\"%s\"><segment address=\"0x%s\"/></library>\n",
1910 dll.name.c_str (), paddress (dll.base_addr));
1912 document += "</library-list>\n";
1914 if (offset > document.length ())
1915 return -1;
1917 if (offset + len > document.length ())
1918 len = document.length () - offset;
1920 memcpy (readbuf, &document[offset], len);
1922 return len;
1925 /* Handle qXfer:libraries-svr4:read. */
1927 static int
1928 handle_qxfer_libraries_svr4 (const char *annex,
1929 gdb_byte *readbuf, const gdb_byte *writebuf,
1930 ULONGEST offset, LONGEST len)
1932 if (writebuf != NULL)
1933 return -2;
1935 if (current_thread == NULL
1936 || !the_target->supports_qxfer_libraries_svr4 ())
1937 return -1;
1939 return the_target->qxfer_libraries_svr4 (annex, readbuf, writebuf,
1940 offset, len);
1943 /* Handle qXfer:osadata:read. */
1945 static int
1946 handle_qxfer_osdata (const char *annex,
1947 gdb_byte *readbuf, const gdb_byte *writebuf,
1948 ULONGEST offset, LONGEST len)
1950 if (!the_target->supports_qxfer_osdata () || writebuf != NULL)
1951 return -2;
1953 return the_target->qxfer_osdata (annex, readbuf, NULL, offset, len);
1956 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1958 static int
1959 handle_qxfer_siginfo (const char *annex,
1960 gdb_byte *readbuf, const gdb_byte *writebuf,
1961 ULONGEST offset, LONGEST len)
1963 if (!the_target->supports_qxfer_siginfo ())
1964 return -2;
1966 if (annex[0] != '\0' || current_thread == NULL)
1967 return -1;
1969 return the_target->qxfer_siginfo (annex, readbuf, writebuf, offset, len);
1972 /* Helper for handle_qxfer_threads_proper.
1973 Emit the XML to describe the thread of INF. */
1975 static void
1976 handle_qxfer_threads_worker (thread_info *thread, std::string *buffer)
1978 ptid_t ptid = thread->id;
1979 char ptid_s[100];
1980 int core = target_core_of_thread (ptid);
1981 char core_s[21];
1982 const char *name = target_thread_name (ptid);
1983 int handle_len;
1984 gdb_byte *handle;
1985 bool handle_status = target_thread_handle (ptid, &handle, &handle_len);
1987 /* If this is a (v)fork/clone child (has a (v)fork/clone parent),
1988 GDB does not yet know about this thread, and must not know about
1989 it until it gets the corresponding (v)fork/clone event. Exclude
1990 this thread from the list. */
1991 if (target_thread_pending_parent (thread) != nullptr)
1992 return;
1994 write_ptid (ptid_s, ptid);
1996 string_xml_appendf (*buffer, "<thread id=\"%s\"", ptid_s);
1998 if (core != -1)
2000 sprintf (core_s, "%d", core);
2001 string_xml_appendf (*buffer, " core=\"%s\"", core_s);
2004 if (name != NULL)
2005 string_xml_appendf (*buffer, " name=\"%s\"", name);
2007 if (handle_status)
2009 char *handle_s = (char *) alloca (handle_len * 2 + 1);
2010 bin2hex (handle, handle_s, handle_len);
2011 string_xml_appendf (*buffer, " handle=\"%s\"", handle_s);
2014 string_xml_appendf (*buffer, "/>\n");
2017 /* Helper for handle_qxfer_threads. Return true on success, false
2018 otherwise. */
2020 static bool
2021 handle_qxfer_threads_proper (std::string *buffer)
2023 *buffer += "<threads>\n";
2025 /* The target may need to access memory and registers (e.g. via
2026 libthread_db) to fetch thread properties. Even if don't need to
2027 stop threads to access memory, we still will need to be able to
2028 access registers, and other ptrace accesses like
2029 PTRACE_GET_THREAD_AREA that require a paused thread. Pause all
2030 threads here, so that we pause each thread at most once for all
2031 accesses. */
2032 if (non_stop)
2033 target_pause_all (true);
2035 for_each_thread ([&] (thread_info *thread)
2037 handle_qxfer_threads_worker (thread, buffer);
2040 if (non_stop)
2041 target_unpause_all (true);
2043 *buffer += "</threads>\n";
2044 return true;
2047 /* Handle qXfer:threads:read. */
2049 static int
2050 handle_qxfer_threads (const char *annex,
2051 gdb_byte *readbuf, const gdb_byte *writebuf,
2052 ULONGEST offset, LONGEST len)
2054 static std::string result;
2056 if (writebuf != NULL)
2057 return -2;
2059 if (annex[0] != '\0')
2060 return -1;
2062 if (offset == 0)
2064 /* When asked for data at offset 0, generate everything and store into
2065 'result'. Successive reads will be served off 'result'. */
2066 result.clear ();
2068 bool res = handle_qxfer_threads_proper (&result);
2070 if (!res)
2071 return -1;
2074 if (offset >= result.length ())
2076 /* We're out of data. */
2077 result.clear ();
2078 return 0;
2081 if (len > result.length () - offset)
2082 len = result.length () - offset;
2084 memcpy (readbuf, result.c_str () + offset, len);
2086 return len;
2089 /* Handle qXfer:traceframe-info:read. */
2091 static int
2092 handle_qxfer_traceframe_info (const char *annex,
2093 gdb_byte *readbuf, const gdb_byte *writebuf,
2094 ULONGEST offset, LONGEST len)
2096 client_state &cs = get_client_state ();
2097 static std::string result;
2099 if (writebuf != NULL)
2100 return -2;
2102 if (!target_running () || annex[0] != '\0' || cs.current_traceframe == -1)
2103 return -1;
2105 if (offset == 0)
2107 /* When asked for data at offset 0, generate everything and
2108 store into 'result'. Successive reads will be served off
2109 'result'. */
2110 result.clear ();
2112 traceframe_read_info (cs.current_traceframe, &result);
2115 if (offset >= result.length ())
2117 /* We're out of data. */
2118 result.clear ();
2119 return 0;
2122 if (len > result.length () - offset)
2123 len = result.length () - offset;
2125 memcpy (readbuf, result.c_str () + offset, len);
2126 return len;
2129 /* Handle qXfer:fdpic:read. */
2131 static int
2132 handle_qxfer_fdpic (const char *annex, gdb_byte *readbuf,
2133 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
2135 if (!the_target->supports_read_loadmap ())
2136 return -2;
2138 if (current_thread == NULL)
2139 return -1;
2141 return the_target->read_loadmap (annex, offset, readbuf, len);
2144 /* Handle qXfer:btrace:read. */
2146 static int
2147 handle_qxfer_btrace (const char *annex,
2148 gdb_byte *readbuf, const gdb_byte *writebuf,
2149 ULONGEST offset, LONGEST len)
2151 client_state &cs = get_client_state ();
2152 static std::string cache;
2153 thread_info *thread;
2154 enum btrace_read_type type;
2155 int result;
2157 if (writebuf != NULL)
2158 return -2;
2160 if (cs.general_thread == null_ptid
2161 || cs.general_thread == minus_one_ptid)
2163 strcpy (cs.own_buf, "E.Must select a single thread.");
2164 return -3;
2167 thread = find_thread_ptid (cs.general_thread);
2168 if (thread == NULL)
2170 strcpy (cs.own_buf, "E.No such thread.");
2171 return -3;
2174 if (thread->btrace == NULL)
2176 strcpy (cs.own_buf, "E.Btrace not enabled.");
2177 return -3;
2180 if (strcmp (annex, "all") == 0)
2181 type = BTRACE_READ_ALL;
2182 else if (strcmp (annex, "new") == 0)
2183 type = BTRACE_READ_NEW;
2184 else if (strcmp (annex, "delta") == 0)
2185 type = BTRACE_READ_DELTA;
2186 else
2188 strcpy (cs.own_buf, "E.Bad annex.");
2189 return -3;
2192 if (offset == 0)
2194 cache.clear ();
2198 result = target_read_btrace (thread->btrace, &cache, type);
2199 if (result != 0)
2200 memcpy (cs.own_buf, cache.c_str (), cache.length ());
2202 catch (const gdb_exception_error &exception)
2204 sprintf (cs.own_buf, "E.%s", exception.what ());
2205 result = -1;
2208 if (result != 0)
2209 return -3;
2211 else if (offset > cache.length ())
2213 cache.clear ();
2214 return -3;
2217 if (len > cache.length () - offset)
2218 len = cache.length () - offset;
2220 memcpy (readbuf, cache.c_str () + offset, len);
2222 return len;
2225 /* Handle qXfer:btrace-conf:read. */
2227 static int
2228 handle_qxfer_btrace_conf (const char *annex,
2229 gdb_byte *readbuf, const gdb_byte *writebuf,
2230 ULONGEST offset, LONGEST len)
2232 client_state &cs = get_client_state ();
2233 static std::string cache;
2234 thread_info *thread;
2235 int result;
2237 if (writebuf != NULL)
2238 return -2;
2240 if (annex[0] != '\0')
2241 return -1;
2243 if (cs.general_thread == null_ptid
2244 || cs.general_thread == minus_one_ptid)
2246 strcpy (cs.own_buf, "E.Must select a single thread.");
2247 return -3;
2250 thread = find_thread_ptid (cs.general_thread);
2251 if (thread == NULL)
2253 strcpy (cs.own_buf, "E.No such thread.");
2254 return -3;
2257 if (thread->btrace == NULL)
2259 strcpy (cs.own_buf, "E.Btrace not enabled.");
2260 return -3;
2263 if (offset == 0)
2265 cache.clear ();
2269 result = target_read_btrace_conf (thread->btrace, &cache);
2270 if (result != 0)
2271 memcpy (cs.own_buf, cache.c_str (), cache.length ());
2273 catch (const gdb_exception_error &exception)
2275 sprintf (cs.own_buf, "E.%s", exception.what ());
2276 result = -1;
2279 if (result != 0)
2280 return -3;
2282 else if (offset > cache.length ())
2284 cache.clear ();
2285 return -3;
2288 if (len > cache.length () - offset)
2289 len = cache.length () - offset;
2291 memcpy (readbuf, cache.c_str () + offset, len);
2293 return len;
2296 static const struct qxfer qxfer_packets[] =
2298 { "auxv", handle_qxfer_auxv },
2299 { "btrace", handle_qxfer_btrace },
2300 { "btrace-conf", handle_qxfer_btrace_conf },
2301 { "exec-file", handle_qxfer_exec_file},
2302 { "fdpic", handle_qxfer_fdpic},
2303 { "features", handle_qxfer_features },
2304 { "libraries", handle_qxfer_libraries },
2305 { "libraries-svr4", handle_qxfer_libraries_svr4 },
2306 { "osdata", handle_qxfer_osdata },
2307 { "siginfo", handle_qxfer_siginfo },
2308 { "threads", handle_qxfer_threads },
2309 { "traceframe-info", handle_qxfer_traceframe_info },
2312 static int
2313 handle_qxfer (char *own_buf, int packet_len, int *new_packet_len_p)
2315 int i;
2316 char *object;
2317 char *rw;
2318 char *annex;
2319 char *offset;
2321 if (!startswith (own_buf, "qXfer:"))
2322 return 0;
2324 /* Grab the object, r/w and annex. */
2325 if (decode_xfer (own_buf + 6, &object, &rw, &annex, &offset) < 0)
2327 write_enn (own_buf);
2328 return 1;
2331 for (i = 0;
2332 i < sizeof (qxfer_packets) / sizeof (qxfer_packets[0]);
2333 i++)
2335 const struct qxfer *q = &qxfer_packets[i];
2337 if (strcmp (object, q->object) == 0)
2339 if (strcmp (rw, "read") == 0)
2341 unsigned char *data;
2342 int n;
2343 CORE_ADDR ofs;
2344 unsigned int len;
2346 /* Grab the offset and length. */
2347 if (decode_xfer_read (offset, &ofs, &len) < 0)
2349 write_enn (own_buf);
2350 return 1;
2353 /* Read one extra byte, as an indicator of whether there is
2354 more. */
2355 if (len > PBUFSIZ - 2)
2356 len = PBUFSIZ - 2;
2357 data = (unsigned char *) malloc (len + 1);
2358 if (data == NULL)
2360 write_enn (own_buf);
2361 return 1;
2363 n = (*q->xfer) (annex, data, NULL, ofs, len + 1);
2364 if (n == -2)
2366 free (data);
2367 return 0;
2369 else if (n == -3)
2371 /* Preserve error message. */
2373 else if (n < 0)
2374 write_enn (own_buf);
2375 else if (n > len)
2376 *new_packet_len_p = write_qxfer_response (own_buf, data, len, 1);
2377 else
2378 *new_packet_len_p = write_qxfer_response (own_buf, data, n, 0);
2380 free (data);
2381 return 1;
2383 else if (strcmp (rw, "write") == 0)
2385 int n;
2386 unsigned int len;
2387 CORE_ADDR ofs;
2388 unsigned char *data;
2390 strcpy (own_buf, "E00");
2391 data = (unsigned char *) malloc (packet_len - (offset - own_buf));
2392 if (data == NULL)
2394 write_enn (own_buf);
2395 return 1;
2397 if (decode_xfer_write (offset, packet_len - (offset - own_buf),
2398 &ofs, &len, data) < 0)
2400 free (data);
2401 write_enn (own_buf);
2402 return 1;
2405 n = (*q->xfer) (annex, NULL, data, ofs, len);
2406 if (n == -2)
2408 free (data);
2409 return 0;
2411 else if (n == -3)
2413 /* Preserve error message. */
2415 else if (n < 0)
2416 write_enn (own_buf);
2417 else
2418 sprintf (own_buf, "%x", n);
2420 free (data);
2421 return 1;
2424 return 0;
2428 return 0;
2431 /* Compute 32 bit CRC from inferior memory.
2433 On success, return 32 bit CRC.
2434 On failure, return (unsigned long long) -1. */
2436 static unsigned long long
2437 crc32 (CORE_ADDR base, int len, unsigned int crc)
2439 while (len--)
2441 unsigned char byte = 0;
2443 /* Return failure if memory read fails. */
2444 if (read_inferior_memory (base, &byte, 1) != 0)
2445 return (unsigned long long) -1;
2447 crc = xcrc32 (&byte, 1, crc);
2448 base++;
2450 return (unsigned long long) crc;
2453 /* Parse the qMemTags packet request into ADDR and LEN. */
2455 static void
2456 parse_fetch_memtags_request (char *request, CORE_ADDR *addr, size_t *len,
2457 int *type)
2459 gdb_assert (startswith (request, "qMemTags:"));
2461 const char *p = request + strlen ("qMemTags:");
2463 /* Read address and length. */
2464 unsigned int length = 0;
2465 p = decode_m_packet_params (p, addr, &length, ':');
2466 *len = length;
2468 /* Read the tag type. */
2469 ULONGEST tag_type = 0;
2470 p = unpack_varlen_hex (p, &tag_type);
2471 *type = (int) tag_type;
2474 /* Add supported btrace packets to BUF. */
2476 static void
2477 supported_btrace_packets (char *buf)
2479 strcat (buf, ";Qbtrace:bts+");
2480 strcat (buf, ";Qbtrace-conf:bts:size+");
2481 strcat (buf, ";Qbtrace:pt+");
2482 strcat (buf, ";Qbtrace-conf:pt:size+");
2483 strcat (buf, ";Qbtrace-conf:pt:ptwrite+");
2484 strcat (buf, ";Qbtrace-conf:pt:event-tracing+");
2485 strcat (buf, ";Qbtrace:off+");
2486 strcat (buf, ";qXfer:btrace:read+");
2487 strcat (buf, ";qXfer:btrace-conf:read+");
2490 /* Handle all of the extended 'q' packets. */
2492 static void
2493 handle_query (char *own_buf, int packet_len, int *new_packet_len_p)
2495 client_state &cs = get_client_state ();
2496 static owning_intrusive_list<process_info>::iterator process_iter;
2497 static owning_intrusive_list<thread_info>::iterator thread_iter;
2499 auto init_thread_iter = [&] ()
2501 process_iter = all_processes.begin ();
2502 owning_intrusive_list<thread_info> *thread_list;
2504 for (; process_iter != all_processes.end (); ++process_iter)
2506 thread_list = &process_iter->thread_list ();
2507 thread_iter = thread_list->begin ();
2508 if (thread_iter != thread_list->end ())
2509 break;
2511 /* Make sure that there is at least one thread to iterate. */
2512 gdb_assert (process_iter != all_processes.end ());
2513 gdb_assert (thread_iter != thread_list->end ());
2516 auto advance_thread_iter = [&] ()
2518 /* The loop below is written in the natural way as-if we'd always
2519 start at the beginning of the inferior list. This fast forwards
2520 the algorithm to the actual current position. */
2521 owning_intrusive_list<thread_info> *thread_list
2522 = &process_iter->thread_list ();
2523 goto start;
2525 for (; process_iter != all_processes.end (); ++process_iter)
2527 thread_list = &process_iter->thread_list ();
2528 thread_iter = thread_list->begin ();
2529 while (thread_iter != thread_list->end ())
2531 return;
2532 start:
2533 ++thread_iter;
2538 /* Reply the current thread id. */
2539 if (strcmp ("qC", own_buf) == 0 && !disable_packet_qC)
2541 ptid_t ptid;
2542 require_running_or_return (own_buf);
2544 if (cs.general_thread != null_ptid && cs.general_thread != minus_one_ptid)
2545 ptid = cs.general_thread;
2546 else
2548 init_thread_iter ();
2549 ptid = thread_iter->id;
2552 sprintf (own_buf, "QC");
2553 own_buf += 2;
2554 write_ptid (own_buf, ptid);
2555 return;
2558 if (strcmp ("qSymbol::", own_buf) == 0)
2560 scoped_restore_current_thread restore_thread;
2562 /* For qSymbol, GDB only changes the current thread if the
2563 previous current thread was of a different process. So if
2564 the previous thread is gone, we need to pick another one of
2565 the same process. This can happen e.g., if we followed an
2566 exec in a non-leader thread. */
2567 if (current_thread == NULL)
2569 thread_info *any_thread
2570 = find_any_thread_of_pid (cs.general_thread.pid ());
2571 switch_to_thread (any_thread);
2573 /* Just in case, if we didn't find a thread, then bail out
2574 instead of crashing. */
2575 if (current_thread == NULL)
2577 write_enn (own_buf);
2578 return;
2582 /* GDB is suggesting new symbols have been loaded. This may
2583 mean a new shared library has been detected as loaded, so
2584 take the opportunity to check if breakpoints we think are
2585 inserted, still are. Note that it isn't guaranteed that
2586 we'll see this when a shared library is loaded, and nor will
2587 we see this for unloads (although breakpoints in unloaded
2588 libraries shouldn't trigger), as GDB may not find symbols for
2589 the library at all. We also re-validate breakpoints when we
2590 see a second GDB breakpoint for the same address, and or when
2591 we access breakpoint shadows. */
2592 validate_breakpoints ();
2594 if (target_supports_tracepoints ())
2595 tracepoint_look_up_symbols ();
2597 if (current_thread != NULL)
2598 the_target->look_up_symbols ();
2600 strcpy (own_buf, "OK");
2601 return;
2604 if (!disable_packet_qfThreadInfo)
2606 if (strcmp ("qfThreadInfo", own_buf) == 0)
2608 require_running_or_return (own_buf);
2609 init_thread_iter ();
2611 *own_buf++ = 'm';
2612 ptid_t ptid = thread_iter->id;
2613 write_ptid (own_buf, ptid);
2614 advance_thread_iter ();
2615 return;
2618 if (strcmp ("qsThreadInfo", own_buf) == 0)
2620 require_running_or_return (own_buf);
2621 /* We're done if the process iterator hits the end of the
2622 process list. */
2623 if (process_iter != all_processes.end ())
2625 *own_buf++ = 'm';
2626 ptid_t ptid = thread_iter->id;
2627 write_ptid (own_buf, ptid);
2628 advance_thread_iter ();
2629 return;
2631 else
2633 sprintf (own_buf, "l");
2634 return;
2639 if (the_target->supports_read_offsets ()
2640 && strcmp ("qOffsets", own_buf) == 0)
2642 CORE_ADDR text, data;
2644 require_running_or_return (own_buf);
2645 if (the_target->read_offsets (&text, &data))
2646 sprintf (own_buf, "Text=%lX;Data=%lX;Bss=%lX",
2647 (long)text, (long)data, (long)data);
2648 else
2649 write_enn (own_buf);
2651 return;
2654 /* Protocol features query. */
2655 if (startswith (own_buf, "qSupported")
2656 && (own_buf[10] == ':' || own_buf[10] == '\0'))
2658 char *p = &own_buf[10];
2659 int gdb_supports_qRelocInsn = 0;
2661 /* Process each feature being provided by GDB. The first
2662 feature will follow a ':', and latter features will follow
2663 ';'. */
2664 if (*p == ':')
2666 std::vector<std::string> qsupported;
2667 std::vector<const char *> unknowns;
2669 /* Two passes, to avoid nested strtok calls in
2670 target_process_qsupported. */
2671 char *saveptr;
2672 for (p = strtok_r (p + 1, ";", &saveptr);
2673 p != NULL;
2674 p = strtok_r (NULL, ";", &saveptr))
2675 qsupported.emplace_back (p);
2677 for (const std::string &feature : qsupported)
2679 if (feature == "multiprocess+")
2681 /* GDB supports and wants multi-process support if
2682 possible. */
2683 if (target_supports_multi_process ())
2684 cs.multi_process = 1;
2686 else if (feature == "qRelocInsn+")
2688 /* GDB supports relocate instruction requests. */
2689 gdb_supports_qRelocInsn = 1;
2691 else if (feature == "swbreak+")
2693 /* GDB wants us to report whether a trap is caused
2694 by a software breakpoint and for us to handle PC
2695 adjustment if necessary on this target. */
2696 if (target_supports_stopped_by_sw_breakpoint ())
2697 cs.swbreak_feature = 1;
2699 else if (feature == "hwbreak+")
2701 /* GDB wants us to report whether a trap is caused
2702 by a hardware breakpoint. */
2703 if (target_supports_stopped_by_hw_breakpoint ())
2704 cs.hwbreak_feature = 1;
2706 else if (feature == "fork-events+")
2708 /* GDB supports and wants fork events if possible. */
2709 if (target_supports_fork_events ())
2710 cs.report_fork_events = 1;
2712 else if (feature == "vfork-events+")
2714 /* GDB supports and wants vfork events if possible. */
2715 if (target_supports_vfork_events ())
2716 cs.report_vfork_events = 1;
2718 else if (feature == "exec-events+")
2720 /* GDB supports and wants exec events if possible. */
2721 if (target_supports_exec_events ())
2722 cs.report_exec_events = 1;
2724 else if (feature == "vContSupported+")
2725 cs.vCont_supported = 1;
2726 else if (feature == "QThreadEvents+")
2728 else if (feature == "QThreadOptions+")
2730 else if (feature == "no-resumed+")
2732 /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
2733 events. */
2734 report_no_resumed = true;
2736 else if (feature == "memory-tagging+")
2738 /* GDB supports memory tagging features. */
2739 if (target_supports_memory_tagging ())
2740 cs.memory_tagging_feature = true;
2742 else if (feature == "error-message+")
2743 cs.error_message_supported = true;
2744 else
2746 /* Move the unknown features all together. */
2747 unknowns.push_back (feature.c_str ());
2751 /* Give the target backend a chance to process the unknown
2752 features. */
2753 target_process_qsupported (unknowns);
2756 sprintf (own_buf,
2757 "PacketSize=%x;QPassSignals+;QProgramSignals+;"
2758 "QStartupWithShell+;QEnvironmentHexEncoded+;"
2759 "QEnvironmentReset+;QEnvironmentUnset+;"
2760 "QSetWorkingDir+;binary-upload+",
2761 PBUFSIZ - 1);
2763 if (target_supports_catch_syscall ())
2764 strcat (own_buf, ";QCatchSyscalls+");
2766 if (the_target->supports_qxfer_libraries_svr4 ())
2767 strcat (own_buf, ";qXfer:libraries-svr4:read+"
2768 ";augmented-libraries-svr4-read+");
2769 else
2771 /* We do not have any hook to indicate whether the non-SVR4 target
2772 backend supports qXfer:libraries:read, so always report it. */
2773 strcat (own_buf, ";qXfer:libraries:read+");
2776 if (the_target->supports_read_auxv ())
2777 strcat (own_buf, ";qXfer:auxv:read+");
2779 if (the_target->supports_qxfer_siginfo ())
2780 strcat (own_buf, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2782 if (the_target->supports_read_loadmap ())
2783 strcat (own_buf, ";qXfer:fdpic:read+");
2785 /* We always report qXfer:features:read, as targets may
2786 install XML files on a subsequent call to arch_setup.
2787 If we reported to GDB on startup that we don't support
2788 qXfer:feature:read at all, we will never be re-queried. */
2789 strcat (own_buf, ";qXfer:features:read+");
2791 if (cs.transport_is_reliable)
2792 strcat (own_buf, ";QStartNoAckMode+");
2794 if (the_target->supports_qxfer_osdata ())
2795 strcat (own_buf, ";qXfer:osdata:read+");
2797 if (target_supports_multi_process ())
2798 strcat (own_buf, ";multiprocess+");
2800 if (target_supports_fork_events ())
2801 strcat (own_buf, ";fork-events+");
2803 if (target_supports_vfork_events ())
2804 strcat (own_buf, ";vfork-events+");
2806 if (target_supports_exec_events ())
2807 strcat (own_buf, ";exec-events+");
2809 if (target_supports_non_stop ())
2810 strcat (own_buf, ";QNonStop+");
2812 if (target_supports_disable_randomization ())
2813 strcat (own_buf, ";QDisableRandomization+");
2815 strcat (own_buf, ";qXfer:threads:read+");
2817 if (target_supports_tracepoints ())
2819 strcat (own_buf, ";ConditionalTracepoints+");
2820 strcat (own_buf, ";TraceStateVariables+");
2821 strcat (own_buf, ";TracepointSource+");
2822 strcat (own_buf, ";DisconnectedTracing+");
2823 if (gdb_supports_qRelocInsn && target_supports_fast_tracepoints ())
2824 strcat (own_buf, ";FastTracepoints+");
2825 strcat (own_buf, ";InstallInTrace+");
2826 strcat (own_buf, ";qXfer:traceframe-info:read+");
2827 strcat (own_buf, ";EnableDisableTracepoints+");
2828 strcat (own_buf, ";QTBuffer:size+");
2829 strcat (own_buf, ";tracenz+");
2832 if (target_supports_hardware_single_step ()
2833 || target_supports_software_single_step () )
2835 strcat (own_buf, ";ConditionalBreakpoints+");
2837 strcat (own_buf, ";BreakpointCommands+");
2839 if (target_supports_agent ())
2840 strcat (own_buf, ";QAgent+");
2842 if (the_target->supports_btrace ())
2843 supported_btrace_packets (own_buf);
2845 if (target_supports_stopped_by_sw_breakpoint ())
2846 strcat (own_buf, ";swbreak+");
2848 if (target_supports_stopped_by_hw_breakpoint ())
2849 strcat (own_buf, ";hwbreak+");
2851 if (the_target->supports_pid_to_exec_file ())
2852 strcat (own_buf, ";qXfer:exec-file:read+");
2854 strcat (own_buf, ";vContSupported+");
2856 gdb_thread_options supported_options = target_supported_thread_options ();
2857 if (supported_options != 0)
2859 char *end_buf = own_buf + strlen (own_buf);
2860 sprintf (end_buf, ";QThreadOptions=%s",
2861 phex_nz (supported_options, sizeof (supported_options)));
2864 strcat (own_buf, ";QThreadEvents+");
2866 strcat (own_buf, ";no-resumed+");
2868 if (target_supports_memory_tagging ())
2869 strcat (own_buf, ";memory-tagging+");
2871 /* Reinitialize components as needed for the new connection. */
2872 hostio_handle_new_gdb_connection ();
2873 target_handle_new_gdb_connection ();
2875 return;
2878 /* Thread-local storage support. */
2879 if (the_target->supports_get_tls_address ()
2880 && startswith (own_buf, "qGetTLSAddr:"))
2882 char *p = own_buf + 12;
2883 CORE_ADDR parts[2], address = 0;
2884 int i, err;
2885 ptid_t ptid = null_ptid;
2887 require_running_or_return (own_buf);
2889 for (i = 0; i < 3; i++)
2891 char *p2;
2892 int len;
2894 if (p == NULL)
2895 break;
2897 p2 = strchr (p, ',');
2898 if (p2)
2900 len = p2 - p;
2901 p2++;
2903 else
2905 len = strlen (p);
2906 p2 = NULL;
2909 if (i == 0)
2910 ptid = read_ptid (p, NULL);
2911 else
2912 decode_address (&parts[i - 1], p, len);
2913 p = p2;
2916 if (p != NULL || i < 3)
2917 err = 1;
2918 else
2920 thread_info *thread = find_thread_ptid (ptid);
2922 if (thread == NULL)
2923 err = 2;
2924 else
2925 err = the_target->get_tls_address (thread, parts[0], parts[1],
2926 &address);
2929 if (err == 0)
2931 strcpy (own_buf, paddress(address));
2932 return;
2934 else if (err > 0)
2936 write_enn (own_buf);
2937 return;
2940 /* Otherwise, pretend we do not understand this packet. */
2943 /* Windows OS Thread Information Block address support. */
2944 if (the_target->supports_get_tib_address ()
2945 && startswith (own_buf, "qGetTIBAddr:"))
2947 const char *annex;
2948 int n;
2949 CORE_ADDR tlb;
2950 ptid_t ptid = read_ptid (own_buf + 12, &annex);
2952 n = the_target->get_tib_address (ptid, &tlb);
2953 if (n == 1)
2955 strcpy (own_buf, paddress(tlb));
2956 return;
2958 else if (n == 0)
2960 write_enn (own_buf);
2961 return;
2963 return;
2966 /* Handle "monitor" commands. */
2967 if (startswith (own_buf, "qRcmd,"))
2969 char *mon = (char *) malloc (PBUFSIZ);
2970 int len = strlen (own_buf + 6);
2972 if (mon == NULL)
2974 write_enn (own_buf);
2975 return;
2978 if ((len % 2) != 0
2979 || hex2bin (own_buf + 6, (gdb_byte *) mon, len / 2) != len / 2)
2981 write_enn (own_buf);
2982 free (mon);
2983 return;
2985 mon[len / 2] = '\0';
2987 write_ok (own_buf);
2989 if (the_target->handle_monitor_command (mon) == 0)
2990 /* Default processing. */
2991 handle_monitor_command (mon, own_buf);
2993 free (mon);
2994 return;
2997 if (startswith (own_buf, "qSearch:memory:"))
2999 require_running_or_return (own_buf);
3000 handle_search_memory (own_buf, packet_len);
3001 return;
3004 if (strcmp (own_buf, "qAttached") == 0
3005 || startswith (own_buf, "qAttached:"))
3007 struct process_info *process;
3009 if (own_buf[sizeof ("qAttached") - 1])
3011 int pid = strtoul (own_buf + sizeof ("qAttached:") - 1, NULL, 16);
3012 process = find_process_pid (pid);
3014 else
3016 require_running_or_return (own_buf);
3017 process = current_process ();
3020 if (process == NULL)
3022 write_enn (own_buf);
3023 return;
3026 strcpy (own_buf, process->attached ? "1" : "0");
3027 return;
3030 if (startswith (own_buf, "qCRC:"))
3032 /* CRC check (compare-section). */
3033 const char *comma;
3034 ULONGEST base;
3035 int len;
3036 unsigned long long crc;
3038 require_running_or_return (own_buf);
3039 comma = unpack_varlen_hex (own_buf + 5, &base);
3040 if (*comma++ != ',')
3042 write_enn (own_buf);
3043 return;
3045 len = strtoul (comma, NULL, 16);
3046 crc = crc32 (base, len, 0xffffffff);
3047 /* Check for memory failure. */
3048 if (crc == (unsigned long long) -1)
3050 write_enn (own_buf);
3051 return;
3053 sprintf (own_buf, "C%lx", (unsigned long) crc);
3054 return;
3057 if (handle_qxfer (own_buf, packet_len, new_packet_len_p))
3058 return;
3060 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf))
3061 return;
3063 /* Handle fetch memory tags packets. */
3064 if (startswith (own_buf, "qMemTags:")
3065 && target_supports_memory_tagging ())
3067 gdb::byte_vector tags;
3068 CORE_ADDR addr = 0;
3069 size_t len = 0;
3070 int type = 0;
3072 require_running_or_return (own_buf);
3074 parse_fetch_memtags_request (own_buf, &addr, &len, &type);
3076 bool ret = the_target->fetch_memtags (addr, len, tags, type);
3078 if (ret)
3079 ret = create_fetch_memtags_reply (own_buf, tags);
3081 if (!ret)
3082 write_enn (own_buf);
3084 *new_packet_len_p = strlen (own_buf);
3085 return;
3088 /* Otherwise we didn't know what packet it was. Say we didn't
3089 understand it. */
3090 own_buf[0] = 0;
3093 static void gdb_wants_all_threads_stopped (void);
3094 static void resume (struct thread_resume *actions, size_t n);
3096 /* The callback that is passed to visit_actioned_threads. */
3097 typedef int (visit_actioned_threads_callback_ftype)
3098 (const struct thread_resume *, thread_info *);
3100 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
3101 true if CALLBACK returns true. Returns false if no matching thread
3102 is found or CALLBACK results false.
3103 Note: This function is itself a callback for find_thread. */
3105 static bool
3106 visit_actioned_threads (thread_info *thread,
3107 const struct thread_resume *actions,
3108 size_t num_actions,
3109 visit_actioned_threads_callback_ftype *callback)
3111 for (size_t i = 0; i < num_actions; i++)
3113 const struct thread_resume *action = &actions[i];
3115 if (action->thread == minus_one_ptid
3116 || action->thread == thread->id
3117 || ((action->thread.pid ()
3118 == thread->id.pid ())
3119 && action->thread.lwp () == -1))
3121 if ((*callback) (action, thread))
3122 return true;
3126 return false;
3129 /* Callback for visit_actioned_threads. If the thread has a pending
3130 status to report, report it now. */
3132 static int
3133 handle_pending_status (const struct thread_resume *resumption,
3134 thread_info *thread)
3136 client_state &cs = get_client_state ();
3137 if (thread->status_pending_p)
3139 thread->status_pending_p = 0;
3141 cs.last_status = thread->last_status;
3142 cs.last_ptid = thread->id;
3143 prepare_resume_reply (cs.own_buf, cs.last_ptid, cs.last_status);
3144 return 1;
3146 return 0;
3149 /* Parse vCont packets. */
3150 static void
3151 handle_v_cont (char *own_buf)
3153 const char *p;
3154 int n = 0, i = 0;
3155 struct thread_resume *resume_info;
3156 struct thread_resume default_action { null_ptid };
3158 /* Count the number of semicolons in the packet. There should be one
3159 for every action. */
3160 p = &own_buf[5];
3161 while (p)
3163 n++;
3164 p++;
3165 p = strchr (p, ';');
3168 resume_info = (struct thread_resume *) malloc (n * sizeof (resume_info[0]));
3169 if (resume_info == NULL)
3170 goto err;
3172 p = &own_buf[5];
3173 while (*p)
3175 p++;
3177 memset (&resume_info[i], 0, sizeof resume_info[i]);
3179 if (p[0] == 's' || p[0] == 'S')
3180 resume_info[i].kind = resume_step;
3181 else if (p[0] == 'r')
3182 resume_info[i].kind = resume_step;
3183 else if (p[0] == 'c' || p[0] == 'C')
3184 resume_info[i].kind = resume_continue;
3185 else if (p[0] == 't')
3186 resume_info[i].kind = resume_stop;
3187 else
3188 goto err;
3190 if (p[0] == 'S' || p[0] == 'C')
3192 char *q;
3193 int sig = strtol (p + 1, &q, 16);
3194 if (p == q)
3195 goto err;
3196 p = q;
3198 if (!gdb_signal_to_host_p ((enum gdb_signal) sig))
3199 goto err;
3200 resume_info[i].sig = gdb_signal_to_host ((enum gdb_signal) sig);
3202 else if (p[0] == 'r')
3204 ULONGEST addr;
3206 p = unpack_varlen_hex (p + 1, &addr);
3207 resume_info[i].step_range_start = addr;
3209 if (*p != ',')
3210 goto err;
3212 p = unpack_varlen_hex (p + 1, &addr);
3213 resume_info[i].step_range_end = addr;
3215 else
3217 p = p + 1;
3220 if (p[0] == 0)
3222 resume_info[i].thread = minus_one_ptid;
3223 default_action = resume_info[i];
3225 /* Note: we don't increment i here, we'll overwrite this entry
3226 the next time through. */
3228 else if (p[0] == ':')
3230 const char *q;
3231 ptid_t ptid = read_ptid (p + 1, &q);
3233 if (p == q)
3234 goto err;
3235 p = q;
3236 if (p[0] != ';' && p[0] != 0)
3237 goto err;
3239 resume_info[i].thread = ptid;
3241 i++;
3245 if (i < n)
3246 resume_info[i] = default_action;
3248 resume (resume_info, n);
3249 free (resume_info);
3250 return;
3252 err:
3253 write_enn (own_buf);
3254 free (resume_info);
3255 return;
3258 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
3260 static void
3261 resume (struct thread_resume *actions, size_t num_actions)
3263 client_state &cs = get_client_state ();
3264 if (!non_stop)
3266 /* Check if among the threads that GDB wants actioned, there's
3267 one with a pending status to report. If so, skip actually
3268 resuming/stopping and report the pending event
3269 immediately. */
3271 thread_info *thread_with_status = find_thread ([&] (thread_info *thread)
3273 return visit_actioned_threads (thread, actions, num_actions,
3274 handle_pending_status);
3277 if (thread_with_status != NULL)
3278 return;
3280 enable_async_io ();
3283 the_target->resume (actions, num_actions);
3285 if (non_stop)
3286 write_ok (cs.own_buf);
3287 else
3289 cs.last_ptid = mywait (minus_one_ptid, &cs.last_status, 0, 1);
3291 if (cs.last_status.kind () == TARGET_WAITKIND_NO_RESUMED
3292 && !report_no_resumed)
3294 /* The client does not support this stop reply. At least
3295 return error. */
3296 sprintf (cs.own_buf, "E.No unwaited-for children left.");
3297 disable_async_io ();
3298 return;
3301 if (cs.last_status.kind () != TARGET_WAITKIND_EXITED
3302 && cs.last_status.kind () != TARGET_WAITKIND_SIGNALLED
3303 && cs.last_status.kind () != TARGET_WAITKIND_THREAD_EXITED
3304 && cs.last_status.kind () != TARGET_WAITKIND_NO_RESUMED)
3305 current_thread->last_status = cs.last_status;
3307 /* From the client's perspective, all-stop mode always stops all
3308 threads implicitly (and the target backend has already done
3309 so by now). Tag all threads as "want-stopped", so we don't
3310 resume them implicitly without the client telling us to. */
3311 gdb_wants_all_threads_stopped ();
3312 prepare_resume_reply (cs.own_buf, cs.last_ptid, cs.last_status);
3313 disable_async_io ();
3315 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
3316 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
3317 target_mourn_inferior (cs.last_ptid);
3321 /* Attach to a new program. */
3322 static void
3323 handle_v_attach (char *own_buf)
3325 client_state &cs = get_client_state ();
3327 int pid = strtol (own_buf + 8, NULL, 16);
3331 if (attach_inferior (pid) == 0)
3333 /* Don't report shared library events after attaching, even if
3334 some libraries are preloaded. GDB will always poll the
3335 library list. Avoids the "stopped by shared library event"
3336 notice on the GDB side. */
3337 current_process ()->dlls_changed = false;
3339 if (non_stop)
3341 /* In non-stop, we don't send a resume reply. Stop events
3342 will follow up using the normal notification
3343 mechanism. */
3344 write_ok (own_buf);
3346 else
3347 prepare_resume_reply (own_buf, cs.last_ptid, cs.last_status);
3349 else
3351 /* Not supported. */
3352 own_buf[0] = 0;
3355 catch (const gdb_exception_error &exception)
3357 sprintf (own_buf, "E.%s", exception.what ());
3361 /* Decode an argument from the vRun packet buffer. PTR points to the
3362 first hex-encoded character in the buffer, and LEN is the number of
3363 characters to read from the packet buffer.
3365 If the argument decoding is successful, return a buffer containing the
3366 decoded argument, including a null terminator at the end.
3368 If the argument decoding fails for any reason, return nullptr. */
3370 static gdb::unique_xmalloc_ptr<char>
3371 decode_v_run_arg (const char *ptr, size_t len)
3373 /* Two hex characters are required for each decoded byte. */
3374 if (len % 2 != 0)
3375 return nullptr;
3377 /* The length in bytes needed for the decoded argument. */
3378 len /= 2;
3380 /* Buffer to decode the argument into. The '+ 1' is for the null
3381 terminator we will add. */
3382 char *arg = (char *) xmalloc (len + 1);
3384 /* Decode the argument from the packet and add a null terminator. We do
3385 this within a try block as invalid characters within the PTR buffer
3386 will cause hex2bin to throw an exception. Our caller relies on us
3387 returning nullptr in order to clean up some memory allocations. */
3390 hex2bin (ptr, (gdb_byte *) arg, len);
3391 arg[len] = '\0';
3393 catch (const gdb_exception_error &exception)
3395 return nullptr;
3398 return gdb::unique_xmalloc_ptr<char> (arg);
3401 /* Run a new program. */
3402 static void
3403 handle_v_run (char *own_buf)
3405 client_state &cs = get_client_state ();
3406 char *p, *next_p;
3407 std::vector<char *> new_argv;
3408 gdb::unique_xmalloc_ptr<char> new_program_name;
3409 int i;
3411 for (i = 0, p = own_buf + strlen ("vRun;");
3412 /* Exit condition is at the end of the loop. */;
3413 p = next_p + 1, ++i)
3415 next_p = strchr (p, ';');
3416 if (next_p == NULL)
3417 next_p = p + strlen (p);
3419 if (i == 0 && p == next_p)
3421 /* No program specified. */
3422 gdb_assert (new_program_name == nullptr);
3424 else if (p == next_p)
3426 /* Empty argument. */
3427 new_argv.push_back (xstrdup (""));
3429 else
3431 /* The length of the argument string in the packet. */
3432 size_t len = next_p - p;
3434 gdb::unique_xmalloc_ptr<char> arg = decode_v_run_arg (p, len);
3435 if (arg == nullptr)
3437 write_enn (own_buf);
3438 free_vector_argv (new_argv);
3439 return;
3442 if (i == 0)
3443 new_program_name = std::move (arg);
3444 else
3445 new_argv.push_back (arg.release ());
3447 if (*next_p == '\0')
3448 break;
3451 if (new_program_name == nullptr)
3453 /* GDB didn't specify a program to run. Use the program from the
3454 last run with the new argument list. */
3455 if (program_path.get () == nullptr)
3457 write_enn (own_buf);
3458 free_vector_argv (new_argv);
3459 return;
3462 else
3463 program_path.set (new_program_name.get ());
3465 program_args = construct_inferior_arguments (new_argv);
3466 free_vector_argv (new_argv);
3470 target_create_inferior (program_path.get (), program_args);
3472 catch (const gdb_exception_error &exception)
3474 sprintf (own_buf, "E.%s", exception.what ());
3475 return;
3478 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
3480 prepare_resume_reply (own_buf, cs.last_ptid, cs.last_status);
3482 /* In non-stop, sending a resume reply doesn't set the general
3483 thread, but GDB assumes a vRun sets it (this is so GDB can
3484 query which is the main thread of the new inferior. */
3485 if (non_stop)
3486 cs.general_thread = cs.last_ptid;
3488 else
3489 write_enn (own_buf);
3492 /* Kill process. */
3493 static void
3494 handle_v_kill (char *own_buf)
3496 client_state &cs = get_client_state ();
3497 int pid;
3498 char *p = &own_buf[6];
3499 if (cs.multi_process)
3500 pid = strtol (p, NULL, 16);
3501 else
3502 pid = signal_pid;
3504 process_info *proc = find_process_pid (pid);
3506 if (proc != nullptr && kill_inferior (proc) == 0)
3508 cs.last_status.set_signalled (GDB_SIGNAL_KILL);
3509 cs.last_ptid = ptid_t (pid);
3510 discard_queued_stop_replies (cs.last_ptid);
3511 write_ok (own_buf);
3513 else
3514 write_enn (own_buf);
3517 /* Handle all of the extended 'v' packets. */
3518 void
3519 handle_v_requests (char *own_buf, int packet_len, int *new_packet_len)
3521 client_state &cs = get_client_state ();
3522 if (!disable_packet_vCont)
3524 if (strcmp (own_buf, "vCtrlC") == 0)
3526 the_target->request_interrupt ();
3527 write_ok (own_buf);
3528 return;
3531 if (startswith (own_buf, "vCont;"))
3533 handle_v_cont (own_buf);
3534 return;
3537 if (startswith (own_buf, "vCont?"))
3539 strcpy (own_buf, "vCont;c;C;t");
3541 if (target_supports_hardware_single_step ()
3542 || target_supports_software_single_step ()
3543 || !cs.vCont_supported)
3545 /* If target supports single step either by hardware or by
3546 software, add actions s and S to the list of supported
3547 actions. On the other hand, if GDB doesn't request the
3548 supported vCont actions in qSupported packet, add s and
3549 S to the list too. */
3550 own_buf = own_buf + strlen (own_buf);
3551 strcpy (own_buf, ";s;S");
3554 if (target_supports_range_stepping ())
3556 own_buf = own_buf + strlen (own_buf);
3557 strcpy (own_buf, ";r");
3559 return;
3563 if (startswith (own_buf, "vFile:")
3564 && handle_vFile (own_buf, packet_len, new_packet_len))
3565 return;
3567 if (startswith (own_buf, "vAttach;"))
3569 if ((!extended_protocol || !cs.multi_process) && target_running ())
3571 fprintf (stderr, "Already debugging a process\n");
3572 write_enn (own_buf);
3573 return;
3575 handle_v_attach (own_buf);
3576 return;
3579 if (startswith (own_buf, "vRun;"))
3581 if ((!extended_protocol || !cs.multi_process) && target_running ())
3583 fprintf (stderr, "Already debugging a process\n");
3584 write_enn (own_buf);
3585 return;
3587 handle_v_run (own_buf);
3588 return;
3591 if (startswith (own_buf, "vKill;"))
3593 if (!target_running ())
3595 fprintf (stderr, "No process to kill\n");
3596 write_enn (own_buf);
3597 return;
3599 handle_v_kill (own_buf);
3600 return;
3603 if (handle_notif_ack (own_buf, packet_len))
3604 return;
3606 /* Otherwise we didn't know what packet it was. Say we didn't
3607 understand it. */
3608 own_buf[0] = 0;
3609 return;
3612 /* Resume thread and wait for another event. In non-stop mode,
3613 don't really wait here, but return immediately to the event
3614 loop. */
3615 static void
3616 myresume (char *own_buf, int step, int sig)
3618 client_state &cs = get_client_state ();
3619 struct thread_resume resume_info[2];
3620 int n = 0;
3621 int valid_cont_thread;
3623 valid_cont_thread = (cs.cont_thread != null_ptid
3624 && cs.cont_thread != minus_one_ptid);
3626 if (step || sig || valid_cont_thread)
3628 resume_info[0].thread = current_thread->id;
3629 if (step)
3630 resume_info[0].kind = resume_step;
3631 else
3632 resume_info[0].kind = resume_continue;
3633 resume_info[0].sig = sig;
3634 n++;
3637 if (!valid_cont_thread)
3639 resume_info[n].thread = minus_one_ptid;
3640 resume_info[n].kind = resume_continue;
3641 resume_info[n].sig = 0;
3642 n++;
3645 resume (resume_info, n);
3648 /* Callback for for_each_thread. Make a new stop reply for each
3649 stopped thread. */
3651 static void
3652 queue_stop_reply_callback (thread_info *thread)
3654 /* For now, assume targets that don't have this callback also don't
3655 manage the thread's last_status field. */
3656 if (!the_target->supports_thread_stopped ())
3658 struct vstop_notif *new_notif = new struct vstop_notif;
3660 new_notif->ptid = thread->id;
3661 new_notif->status = thread->last_status;
3662 /* Pass the last stop reply back to GDB, but don't notify
3663 yet. */
3664 notif_event_enque (&notif_stop, new_notif);
3666 else
3668 if (target_thread_stopped (thread))
3670 threads_debug_printf
3671 ("Reporting thread %s as already stopped with %s",
3672 target_pid_to_str (thread->id).c_str (),
3673 thread->last_status.to_string ().c_str ());
3675 gdb_assert (thread->last_status.kind () != TARGET_WAITKIND_IGNORE);
3677 /* Pass the last stop reply back to GDB, but don't notify
3678 yet. */
3679 queue_stop_reply (thread->id, thread->last_status);
3684 /* Set this inferior threads's state as "want-stopped". We won't
3685 resume this thread until the client gives us another action for
3686 it. */
3688 static void
3689 gdb_wants_thread_stopped (thread_info *thread)
3691 thread->last_resume_kind = resume_stop;
3693 if (thread->last_status.kind () == TARGET_WAITKIND_IGNORE)
3695 /* Most threads are stopped implicitly (all-stop); tag that with
3696 signal 0. */
3697 thread->last_status.set_stopped (GDB_SIGNAL_0);
3701 /* Set all threads' states as "want-stopped". */
3703 static void
3704 gdb_wants_all_threads_stopped (void)
3706 for_each_thread (gdb_wants_thread_stopped);
3709 /* Callback for for_each_thread. If the thread is stopped with an
3710 interesting event, mark it as having a pending event. */
3712 static void
3713 set_pending_status_callback (thread_info *thread)
3715 if (thread->last_status.kind () != TARGET_WAITKIND_STOPPED
3716 || (thread->last_status.sig () != GDB_SIGNAL_0
3717 /* A breakpoint, watchpoint or finished step from a previous
3718 GDB run isn't considered interesting for a new GDB run.
3719 If we left those pending, the new GDB could consider them
3720 random SIGTRAPs. This leaves out real async traps. We'd
3721 have to peek into the (target-specific) siginfo to
3722 distinguish those. */
3723 && thread->last_status.sig () != GDB_SIGNAL_TRAP))
3724 thread->status_pending_p = 1;
3727 /* Status handler for the '?' packet. */
3729 static void
3730 handle_status (char *own_buf)
3732 client_state &cs = get_client_state ();
3734 /* GDB is connected, don't forward events to the target anymore. */
3735 for_each_process ([] (process_info *process) {
3736 process->gdb_detached = 0;
3739 /* In non-stop mode, we must send a stop reply for each stopped
3740 thread. In all-stop mode, just send one for the first stopped
3741 thread we find. */
3743 if (non_stop)
3745 for_each_thread (queue_stop_reply_callback);
3747 /* The first is sent immediately. OK is sent if there is no
3748 stopped thread, which is the same handling of the vStopped
3749 packet (by design). */
3750 notif_write_event (&notif_stop, cs.own_buf);
3752 else
3754 thread_info *thread = NULL;
3756 target_pause_all (false);
3757 target_stabilize_threads ();
3758 gdb_wants_all_threads_stopped ();
3760 /* We can only report one status, but we might be coming out of
3761 non-stop -- if more than one thread is stopped with
3762 interesting events, leave events for the threads we're not
3763 reporting now pending. They'll be reported the next time the
3764 threads are resumed. Start by marking all interesting events
3765 as pending. */
3766 for_each_thread (set_pending_status_callback);
3768 /* Prefer the last thread that reported an event to GDB (even if
3769 that was a GDB_SIGNAL_TRAP). */
3770 if (cs.last_status.kind () != TARGET_WAITKIND_IGNORE
3771 && cs.last_status.kind () != TARGET_WAITKIND_EXITED
3772 && cs.last_status.kind () != TARGET_WAITKIND_SIGNALLED)
3773 thread = find_thread_ptid (cs.last_ptid);
3775 /* If the last event thread is not found for some reason, look
3776 for some other thread that might have an event to report. */
3777 if (thread == NULL)
3778 thread = find_thread ([] (thread_info *thr_arg)
3780 return thr_arg->status_pending_p;
3783 /* If we're still out of luck, simply pick the first thread in
3784 the thread list. */
3785 if (thread == NULL)
3786 thread = get_first_thread ();
3788 if (thread != NULL)
3790 thread_info *tp = (thread_info *) thread;
3792 /* We're reporting this event, so it's no longer
3793 pending. */
3794 tp->status_pending_p = 0;
3796 /* GDB assumes the current thread is the thread we're
3797 reporting the status for. */
3798 cs.general_thread = thread->id;
3799 set_desired_thread ();
3801 gdb_assert (tp->last_status.kind () != TARGET_WAITKIND_IGNORE);
3802 prepare_resume_reply (own_buf, tp->id, tp->last_status);
3804 else
3805 strcpy (own_buf, "W00");
3809 static void
3810 gdbserver_version (void)
3812 printf ("GNU gdbserver %s%s\n"
3813 "Copyright (C) 2024 Free Software Foundation, Inc.\n"
3814 "gdbserver is free software, covered by the "
3815 "GNU General Public License.\n"
3816 "This gdbserver was configured as \"%s\"\n",
3817 PKGVERSION, version, host_name);
3820 static void
3821 gdbserver_usage (FILE *stream)
3823 fprintf (stream, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3824 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3825 "\tgdbserver [OPTIONS] --multi COMM\n"
3826 "\n"
3827 "COMM may either be a tty device (for serial debugging),\n"
3828 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3829 "stdin/stdout of gdbserver.\n"
3830 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3831 "PID is the process ID to attach to, when --attach is specified.\n"
3832 "\n"
3833 "Operating modes:\n"
3834 "\n"
3835 " --attach Attach to running process PID.\n"
3836 " --multi Start server without a specific program, and\n"
3837 " only quit when explicitly commanded.\n"
3838 " --once Exit after the first connection has closed.\n"
3839 " --help Print this message and then exit.\n"
3840 " --version Display version information and exit.\n"
3841 "\n"
3842 "Other options:\n"
3843 "\n"
3844 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3845 " --disable-randomization\n"
3846 " Run PROG with address space randomization disabled.\n"
3847 " --no-disable-randomization\n"
3848 " Don't disable address space randomization when\n"
3849 " starting PROG.\n"
3850 " --startup-with-shell\n"
3851 " Start PROG using a shell. I.e., execs a shell that\n"
3852 " then execs PROG. (default)\n"
3853 " --no-startup-with-shell\n"
3854 " Exec PROG directly instead of using a shell.\n"
3855 " Disables argument globbing and variable substitution\n"
3856 " on UNIX-like systems.\n"
3857 "\n"
3858 "Debug options:\n"
3859 "\n"
3860 " --debug[=OPT1,OPT2,...]\n"
3861 " Enable debugging output.\n"
3862 " Options:\n"
3863 " all, threads, event-loop, remote\n"
3864 " With no options, 'threads' is assumed.\n"
3865 " Prefix an option with '-' to disable\n"
3866 " debugging of that component.\n"
3867 " --debug-format=OPT1[,OPT2,...]\n"
3868 " Specify extra content in debugging output.\n"
3869 " Options:\n"
3870 " all\n"
3871 " none\n"
3872 " timestamp\n"
3873 " --disable-packet=OPT1[,OPT2,...]\n"
3874 " Disable support for RSP packets or features.\n"
3875 " Options:\n"
3876 " vCont, T, Tthread, qC, qfThreadInfo and \n"
3877 " threads (disable all threading packets).\n"
3878 "\n"
3879 "For more information, consult the GDB manual (available as on-line \n"
3880 "info or a printed manual).\n");
3881 if (REPORT_BUGS_TO[0] && stream == stdout)
3882 fprintf (stream, "Report bugs to \"%s\".\n", REPORT_BUGS_TO);
3885 static void
3886 gdbserver_show_disableable (FILE *stream)
3888 fprintf (stream, "Disableable packets:\n"
3889 " vCont \tAll vCont packets\n"
3890 " qC \tQuerying the current thread\n"
3891 " qfThreadInfo\tThread listing\n"
3892 " Tthread \tPassing the thread specifier in the "
3893 "T stop reply packet\n"
3894 " threads \tAll of the above\n"
3895 " T \tAll 'T' packets\n");
3898 /* Start up the event loop. This is the entry point to the event
3899 loop. */
3901 static void
3902 start_event_loop ()
3904 /* Loop until there is nothing to do. This is the entry point to
3905 the event loop engine. If nothing is ready at this time, wait
3906 for something to happen (via wait_for_event), then process it.
3907 Return when there are no longer event sources to wait for. */
3909 keep_processing_events = true;
3910 while (keep_processing_events)
3912 /* Any events already waiting in the queue? */
3913 int res = gdb_do_one_event ();
3915 /* Was there an error? */
3916 if (res == -1)
3917 break;
3920 /* We are done with the event loop. There are no more event sources
3921 to listen to. So we exit gdbserver. */
3924 static void
3925 kill_inferior_callback (process_info *process)
3927 kill_inferior (process);
3928 discard_queued_stop_replies (ptid_t (process->pid));
3931 /* Call this when exiting gdbserver with possible inferiors that need
3932 to be killed or detached from. */
3934 static void
3935 detach_or_kill_for_exit (void)
3937 /* First print a list of the inferiors we will be killing/detaching.
3938 This is to assist the user, for example, in case the inferior unexpectedly
3939 dies after we exit: did we screw up or did the inferior exit on its own?
3940 Having this info will save some head-scratching. */
3942 if (have_started_inferiors_p ())
3944 fprintf (stderr, "Killing process(es):");
3946 for_each_process ([] (process_info *process) {
3947 if (!process->attached)
3948 fprintf (stderr, " %d", process->pid);
3951 fprintf (stderr, "\n");
3953 if (have_attached_inferiors_p ())
3955 fprintf (stderr, "Detaching process(es):");
3957 for_each_process ([] (process_info *process) {
3958 if (process->attached)
3959 fprintf (stderr, " %d", process->pid);
3962 fprintf (stderr, "\n");
3965 /* Now we can kill or detach the inferiors. */
3966 for_each_process ([] (process_info *process) {
3967 int pid = process->pid;
3969 if (process->attached)
3970 detach_inferior (process);
3971 else
3972 kill_inferior (process);
3974 discard_queued_stop_replies (ptid_t (pid));
3978 /* Value that will be passed to exit(3) when gdbserver exits. */
3979 static int exit_code;
3981 /* Wrapper for detach_or_kill_for_exit that catches and prints
3982 errors. */
3984 static void
3985 detach_or_kill_for_exit_cleanup ()
3989 detach_or_kill_for_exit ();
3991 catch (const gdb_exception &exception)
3993 fflush (stdout);
3994 fprintf (stderr, "Detach or kill failed: %s\n",
3995 exception.what ());
3996 exit_code = 1;
4000 #if GDB_SELF_TEST
4002 namespace selftests {
4004 static void
4005 test_memory_tagging_functions (void)
4007 /* Setup testing. */
4008 gdb::char_vector packet;
4009 gdb::byte_vector tags, bv;
4010 std::string expected;
4011 packet.resize (32000);
4012 CORE_ADDR addr;
4013 size_t len;
4014 int type;
4016 /* Test parsing a qMemTags request. */
4018 /* Valid request, addr, len and type updated. */
4019 addr = 0xff;
4020 len = 255;
4021 type = 255;
4022 strcpy (packet.data (), "qMemTags:0,0:0");
4023 parse_fetch_memtags_request (packet.data (), &addr, &len, &type);
4024 SELF_CHECK (addr == 0 && len == 0 && type == 0);
4026 /* Valid request, addr, len and type updated. */
4027 addr = 0;
4028 len = 0;
4029 type = 0;
4030 strcpy (packet.data (), "qMemTags:deadbeef,ff:5");
4031 parse_fetch_memtags_request (packet.data (), &addr, &len, &type);
4032 SELF_CHECK (addr == 0xdeadbeef && len == 255 && type == 5);
4034 /* Test creating a qMemTags reply. */
4036 /* Non-empty tag data. */
4037 bv.resize (0);
4039 for (int i = 0; i < 5; i++)
4040 bv.push_back (i);
4042 expected = "m0001020304";
4043 SELF_CHECK (create_fetch_memtags_reply (packet.data (), bv) == true);
4044 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
4046 /* Test parsing a QMemTags request. */
4048 /* Valid request and empty tag data: addr, len, type and tags updated. */
4049 addr = 0xff;
4050 len = 255;
4051 type = 255;
4052 tags.resize (5);
4053 strcpy (packet.data (), "QMemTags:0,0:0:");
4054 SELF_CHECK (parse_store_memtags_request (packet.data (),
4055 &addr, &len, tags, &type) == true);
4056 SELF_CHECK (addr == 0 && len == 0 && type == 0 && tags.size () == 0);
4058 /* Valid request and non-empty tag data: addr, len, type
4059 and tags updated. */
4060 addr = 0;
4061 len = 0;
4062 type = 0;
4063 tags.resize (0);
4064 strcpy (packet.data (),
4065 "QMemTags:deadbeef,ff:5:0001020304");
4066 SELF_CHECK (parse_store_memtags_request (packet.data (), &addr, &len, tags,
4067 &type) == true);
4068 SELF_CHECK (addr == 0xdeadbeef && len == 255 && type == 5
4069 && tags.size () == 5);
4072 } // namespace selftests
4073 #endif /* GDB_SELF_TEST */
4075 /* Main function. This is called by the real "main" function,
4076 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
4078 [[noreturn]] static void
4079 captured_main (int argc, char *argv[])
4081 int bad_attach;
4082 int pid;
4083 char *arg_end;
4084 const char *port = NULL;
4085 char **next_arg = &argv[1];
4086 volatile int multi_mode = 0;
4087 volatile int attach = 0;
4088 int was_running;
4089 bool selftest = false;
4090 #if GDB_SELF_TEST
4091 std::vector<const char *> selftest_filters;
4093 selftests::register_test ("remote_memory_tagging",
4094 selftests::test_memory_tagging_functions);
4095 #endif
4097 current_directory = getcwd (NULL, 0);
4098 client_state &cs = get_client_state ();
4100 if (current_directory == NULL)
4102 error (_("Could not find current working directory: %s"),
4103 safe_strerror (errno));
4106 while (*next_arg != NULL && **next_arg == '-')
4108 if (strcmp (*next_arg, "--version") == 0)
4110 gdbserver_version ();
4111 exit (0);
4113 else if (strcmp (*next_arg, "--help") == 0)
4115 gdbserver_usage (stdout);
4116 exit (0);
4118 else if (strcmp (*next_arg, "--attach") == 0)
4119 attach = 1;
4120 else if (strcmp (*next_arg, "--multi") == 0)
4121 multi_mode = 1;
4122 else if (strcmp (*next_arg, "--wrapper") == 0)
4124 char **tmp;
4126 next_arg++;
4128 tmp = next_arg;
4129 while (*next_arg != NULL && strcmp (*next_arg, "--") != 0)
4131 wrapper_argv += *next_arg;
4132 wrapper_argv += ' ';
4133 next_arg++;
4136 if (!wrapper_argv.empty ())
4138 /* Erase the last whitespace. */
4139 wrapper_argv.erase (wrapper_argv.end () - 1);
4142 if (next_arg == tmp || *next_arg == NULL)
4144 gdbserver_usage (stderr);
4145 exit (1);
4148 /* Consume the "--". */
4149 *next_arg = NULL;
4151 else if (startswith (*next_arg, "--debug="))
4155 parse_debug_options ((*next_arg) + sizeof ("--debug=") - 1);
4157 catch (const gdb_exception_error &exception)
4159 fflush (stdout);
4160 fprintf (stderr, "gdbserver: %s\n", exception.what ());
4161 exit (1);
4164 else if (strcmp (*next_arg, "--debug") == 0)
4168 parse_debug_options ("");
4170 catch (const gdb_exception_error &exception)
4172 fflush (stdout);
4173 fprintf (stderr, "gdbserver: %s\n", exception.what ());
4174 exit (1);
4177 else if (startswith (*next_arg, "--debug-format="))
4179 std::string error_msg
4180 = parse_debug_format_options ((*next_arg)
4181 + sizeof ("--debug-format=") - 1, 0);
4183 if (!error_msg.empty ())
4185 fprintf (stderr, "%s", error_msg.c_str ());
4186 exit (1);
4189 else if (startswith (*next_arg, "--debug-file="))
4190 debug_set_output ((*next_arg) + sizeof ("--debug-file=") -1);
4191 else if (strcmp (*next_arg, "--disable-packet") == 0)
4193 gdbserver_show_disableable (stdout);
4194 exit (0);
4196 else if (startswith (*next_arg, "--disable-packet="))
4198 char *packets = *next_arg += sizeof ("--disable-packet=") - 1;
4199 char *saveptr;
4200 for (char *tok = strtok_r (packets, ",", &saveptr);
4201 tok != NULL;
4202 tok = strtok_r (NULL, ",", &saveptr))
4204 if (strcmp ("vCont", tok) == 0)
4205 disable_packet_vCont = true;
4206 else if (strcmp ("Tthread", tok) == 0)
4207 disable_packet_Tthread = true;
4208 else if (strcmp ("qC", tok) == 0)
4209 disable_packet_qC = true;
4210 else if (strcmp ("qfThreadInfo", tok) == 0)
4211 disable_packet_qfThreadInfo = true;
4212 else if (strcmp ("T", tok) == 0)
4213 disable_packet_T = true;
4214 else if (strcmp ("threads", tok) == 0)
4216 disable_packet_vCont = true;
4217 disable_packet_Tthread = true;
4218 disable_packet_qC = true;
4219 disable_packet_qfThreadInfo = true;
4221 else
4223 fprintf (stderr, "Don't know how to disable \"%s\".\n\n",
4224 tok);
4225 gdbserver_show_disableable (stderr);
4226 exit (1);
4230 else if (strcmp (*next_arg, "-") == 0)
4232 /* "-" specifies a stdio connection and is a form of port
4233 specification. */
4234 port = STDIO_CONNECTION_NAME;
4236 /* Implying --once here prevents a hang after stdin has been closed. */
4237 run_once = true;
4239 next_arg++;
4240 break;
4242 else if (strcmp (*next_arg, "--disable-randomization") == 0)
4243 cs.disable_randomization = 1;
4244 else if (strcmp (*next_arg, "--no-disable-randomization") == 0)
4245 cs.disable_randomization = 0;
4246 else if (strcmp (*next_arg, "--startup-with-shell") == 0)
4247 startup_with_shell = true;
4248 else if (strcmp (*next_arg, "--no-startup-with-shell") == 0)
4249 startup_with_shell = false;
4250 else if (strcmp (*next_arg, "--once") == 0)
4251 run_once = true;
4252 else if (strcmp (*next_arg, "--selftest") == 0)
4253 selftest = true;
4254 else if (startswith (*next_arg, "--selftest="))
4256 selftest = true;
4258 #if GDB_SELF_TEST
4259 const char *filter = *next_arg + strlen ("--selftest=");
4260 if (*filter == '\0')
4262 fprintf (stderr, _("Error: selftest filter is empty.\n"));
4263 exit (1);
4266 selftest_filters.push_back (filter);
4267 #endif
4269 else
4271 fprintf (stderr, "Unknown argument: %s\n", *next_arg);
4272 exit (1);
4275 next_arg++;
4276 continue;
4279 if (port == NULL)
4281 port = *next_arg;
4282 next_arg++;
4284 if ((port == NULL || (!attach && !multi_mode && *next_arg == NULL))
4285 && !selftest)
4287 gdbserver_usage (stderr);
4288 exit (1);
4291 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
4292 opened by remote_prepare. */
4293 notice_open_fds ();
4295 save_original_signals_state (false);
4297 /* We need to know whether the remote connection is stdio before
4298 starting the inferior. Inferiors created in this scenario have
4299 stdin,stdout redirected. So do this here before we call
4300 start_inferior. */
4301 if (port != NULL)
4302 remote_prepare (port);
4304 bad_attach = 0;
4305 pid = 0;
4307 /* --attach used to come after PORT, so allow it there for
4308 compatibility. */
4309 if (*next_arg != NULL && strcmp (*next_arg, "--attach") == 0)
4311 attach = 1;
4312 next_arg++;
4315 if (attach
4316 && (*next_arg == NULL
4317 || (*next_arg)[0] == '\0'
4318 || (pid = strtoul (*next_arg, &arg_end, 0)) == 0
4319 || *arg_end != '\0'
4320 || next_arg[1] != NULL))
4321 bad_attach = 1;
4323 if (bad_attach)
4325 gdbserver_usage (stderr);
4326 exit (1);
4329 /* Gather information about the environment. */
4330 our_environ = gdb_environ::from_host_environ ();
4332 initialize_async_io ();
4333 initialize_low ();
4334 have_job_control ();
4335 if (target_supports_tracepoints ())
4336 initialize_tracepoint ();
4338 mem_buf = (unsigned char *) xmalloc (PBUFSIZ);
4340 if (selftest)
4342 #if GDB_SELF_TEST
4343 selftests::run_tests (selftest_filters);
4344 #else
4345 printf (_("Selftests have been disabled for this build.\n"));
4346 #endif
4347 throw_quit ("Quit");
4350 if (pid == 0 && *next_arg != NULL)
4352 program_path.set (next_arg[0]);
4354 int n = argc - (next_arg - argv);
4355 program_args
4356 = construct_inferior_arguments ({&next_arg[1], &next_arg[n]});
4358 /* Wait till we are at first instruction in program. */
4359 target_create_inferior (program_path.get (), program_args);
4361 /* We are now (hopefully) stopped at the first instruction of
4362 the target process. This assumes that the target process was
4363 successfully created. */
4365 else if (pid != 0)
4367 if (attach_inferior (pid) == -1)
4368 error ("Attaching not supported on this target");
4370 /* Otherwise succeeded. */
4372 else
4374 cs.last_status.set_exited (0);
4375 cs.last_ptid = minus_one_ptid;
4378 SCOPE_EXIT { detach_or_kill_for_exit_cleanup (); };
4380 /* Don't report shared library events on the initial connection,
4381 even if some libraries are preloaded. Avoids the "stopped by
4382 shared library event" notice on gdb side. */
4383 if (current_thread != nullptr)
4384 current_process ()->dlls_changed = false;
4386 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
4387 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
4388 was_running = 0;
4389 else
4390 was_running = 1;
4392 if (!was_running && !multi_mode)
4393 error ("No program to debug");
4395 while (1)
4397 cs.noack_mode = 0;
4398 cs.multi_process = 0;
4399 cs.report_fork_events = 0;
4400 cs.report_vfork_events = 0;
4401 cs.report_exec_events = 0;
4402 /* Be sure we're out of tfind mode. */
4403 cs.current_traceframe = -1;
4404 cs.cont_thread = null_ptid;
4405 cs.swbreak_feature = 0;
4406 cs.hwbreak_feature = 0;
4407 cs.vCont_supported = 0;
4408 cs.memory_tagging_feature = false;
4409 cs.error_message_supported = false;
4411 remote_open (port);
4415 /* Wait for events. This will return when all event sources
4416 are removed from the event loop. */
4417 start_event_loop ();
4419 /* If an exit was requested (using the "monitor exit"
4420 command), terminate now. */
4421 if (exit_requested)
4422 throw_quit ("Quit");
4424 /* The only other way to get here is for getpkt to fail:
4426 - If --once was specified, we're done.
4428 - If not in extended-remote mode, and we're no longer
4429 debugging anything, simply exit: GDB has disconnected
4430 after processing the last process exit.
4432 - Otherwise, close the connection and reopen it at the
4433 top of the loop. */
4434 if (run_once || (!extended_protocol && !target_running ()))
4435 throw_quit ("Quit");
4437 fprintf (stderr,
4438 "Remote side has terminated connection. "
4439 "GDBserver will reopen the connection.\n");
4441 /* Get rid of any pending statuses. An eventual reconnection
4442 (by the same GDB instance or another) will refresh all its
4443 state from scratch. */
4444 discard_queued_stop_replies (minus_one_ptid);
4445 for_each_thread ([] (thread_info *thread)
4447 thread->status_pending_p = 0;
4450 if (tracing)
4452 if (disconnected_tracing)
4454 /* Try to enable non-stop/async mode, so we we can
4455 both wait for an async socket accept, and handle
4456 async target events simultaneously. There's also
4457 no point either in having the target always stop
4458 all threads, when we're going to pass signals
4459 down without informing GDB. */
4460 if (!non_stop)
4462 if (the_target->start_non_stop (true))
4463 non_stop = 1;
4465 /* Detaching implicitly resumes all threads;
4466 simply disconnecting does not. */
4469 else
4471 fprintf (stderr,
4472 "Disconnected tracing disabled; "
4473 "stopping trace run.\n");
4474 stop_tracing ();
4478 catch (const gdb_exception_error &exception)
4480 fflush (stdout);
4481 fprintf (stderr, "gdbserver: %s\n", exception.what ());
4483 if (response_needed)
4485 write_enn (cs.own_buf);
4486 putpkt (cs.own_buf);
4489 if (run_once)
4490 throw_quit ("Quit");
4495 /* Main function. */
4498 main (int argc, char *argv[])
4500 setlocale (LC_CTYPE, "");
4504 captured_main (argc, argv);
4506 catch (const gdb_exception &exception)
4508 if (exception.reason == RETURN_ERROR)
4510 fflush (stdout);
4511 fprintf (stderr, "%s\n", exception.what ());
4512 fprintf (stderr, "Exiting\n");
4513 exit_code = 1;
4516 exit (exit_code);
4519 gdb_assert_not_reached ("captured_main should never return");
4522 /* Process options coming from Z packets for a breakpoint. PACKET is
4523 the packet buffer. *PACKET is updated to point to the first char
4524 after the last processed option. */
4526 static void
4527 process_point_options (struct gdb_breakpoint *bp, const char **packet)
4529 const char *dataptr = *packet;
4530 int persist;
4532 /* Check if data has the correct format. */
4533 if (*dataptr != ';')
4534 return;
4536 dataptr++;
4538 while (*dataptr)
4540 if (*dataptr == ';')
4541 ++dataptr;
4543 if (*dataptr == 'X')
4545 /* Conditional expression. */
4546 threads_debug_printf ("Found breakpoint condition.");
4547 if (!add_breakpoint_condition (bp, &dataptr))
4548 dataptr = strchrnul (dataptr, ';');
4550 else if (startswith (dataptr, "cmds:"))
4552 dataptr += strlen ("cmds:");
4553 threads_debug_printf ("Found breakpoint commands %s.", dataptr);
4554 persist = (*dataptr == '1');
4555 dataptr += 2;
4556 if (add_breakpoint_commands (bp, &dataptr, persist))
4557 dataptr = strchrnul (dataptr, ';');
4559 else
4561 fprintf (stderr, "Unknown token %c, ignoring.\n",
4562 *dataptr);
4563 /* Skip tokens until we find one that we recognize. */
4564 dataptr = strchrnul (dataptr, ';');
4567 *packet = dataptr;
4570 /* Event loop callback that handles a serial event. The first byte in
4571 the serial buffer gets us here. We expect characters to arrive at
4572 a brisk pace, so we read the rest of the packet with a blocking
4573 getpkt call. */
4575 static int
4576 process_serial_event (void)
4578 client_state &cs = get_client_state ();
4579 int signal;
4580 unsigned int len;
4581 CORE_ADDR mem_addr;
4582 unsigned char sig;
4583 int packet_len;
4584 int new_packet_len = -1;
4586 disable_async_io ();
4588 response_needed = false;
4589 packet_len = getpkt (cs.own_buf);
4590 if (packet_len <= 0)
4592 remote_close ();
4593 /* Force an event loop break. */
4594 return -1;
4596 response_needed = true;
4598 char ch = cs.own_buf[0];
4599 switch (ch)
4601 case 'q':
4602 handle_query (cs.own_buf, packet_len, &new_packet_len);
4603 break;
4604 case 'Q':
4605 handle_general_set (cs.own_buf);
4606 break;
4607 case 'D':
4608 handle_detach (cs.own_buf);
4609 break;
4610 case '!':
4611 extended_protocol = true;
4612 write_ok (cs.own_buf);
4613 break;
4614 case '?':
4615 handle_status (cs.own_buf);
4616 break;
4617 case 'H':
4618 if (cs.own_buf[1] == 'c' || cs.own_buf[1] == 'g' || cs.own_buf[1] == 's')
4620 require_running_or_break (cs.own_buf);
4622 ptid_t thread_id = read_ptid (&cs.own_buf[2], NULL);
4624 if (thread_id == null_ptid || thread_id == minus_one_ptid)
4625 thread_id = null_ptid;
4626 else if (thread_id.is_pid ())
4628 /* The ptid represents a pid. */
4629 thread_info *thread = find_any_thread_of_pid (thread_id.pid ());
4631 if (thread == NULL)
4633 write_enn (cs.own_buf);
4634 break;
4637 thread_id = thread->id;
4639 else
4641 /* The ptid represents a lwp/tid. */
4642 if (find_thread_ptid (thread_id) == NULL)
4644 write_enn (cs.own_buf);
4645 break;
4649 if (cs.own_buf[1] == 'g')
4651 if (thread_id == null_ptid)
4653 /* GDB is telling us to choose any thread. Check if
4654 the currently selected thread is still valid. If
4655 it is not, select the first available. */
4656 thread_info *thread = find_thread_ptid (cs.general_thread);
4657 if (thread == NULL)
4658 thread = get_first_thread ();
4659 thread_id = thread->id;
4662 cs.general_thread = thread_id;
4663 set_desired_thread ();
4664 gdb_assert (current_thread != NULL);
4666 else if (cs.own_buf[1] == 'c')
4667 cs.cont_thread = thread_id;
4669 write_ok (cs.own_buf);
4671 else
4673 /* Silently ignore it so that gdb can extend the protocol
4674 without compatibility headaches. */
4675 cs.own_buf[0] = '\0';
4677 break;
4678 case 'g':
4679 require_running_or_break (cs.own_buf);
4680 if (cs.current_traceframe >= 0)
4682 struct regcache *regcache
4683 = new_register_cache (current_target_desc ());
4685 if (fetch_traceframe_registers (cs.current_traceframe,
4686 regcache, -1) == 0)
4687 registers_to_string (regcache, cs.own_buf);
4688 else
4689 write_enn (cs.own_buf);
4690 free_register_cache (regcache);
4692 else
4694 struct regcache *regcache;
4696 if (!set_desired_thread ())
4697 write_enn (cs.own_buf);
4698 else
4700 regcache = get_thread_regcache (current_thread);
4701 registers_to_string (regcache, cs.own_buf);
4704 break;
4705 case 'G':
4706 require_running_or_break (cs.own_buf);
4707 if (cs.current_traceframe >= 0)
4708 write_enn (cs.own_buf);
4709 else
4711 struct regcache *regcache;
4713 if (!set_desired_thread ())
4714 write_enn (cs.own_buf);
4715 else
4717 regcache = get_thread_regcache (current_thread);
4718 registers_from_string (regcache, &cs.own_buf[1]);
4719 write_ok (cs.own_buf);
4722 break;
4723 case 'm':
4725 require_running_or_break (cs.own_buf);
4726 decode_m_packet (&cs.own_buf[1], &mem_addr, &len);
4727 int res = gdb_read_memory (mem_addr, mem_buf, len);
4728 if (res < 0)
4729 write_enn (cs.own_buf);
4730 else
4731 bin2hex (mem_buf, cs.own_buf, res);
4733 break;
4734 case 'M':
4735 require_running_or_break (cs.own_buf);
4736 decode_M_packet (&cs.own_buf[1], &mem_addr, &len, &mem_buf);
4737 if (gdb_write_memory (mem_addr, mem_buf, len) == 0)
4738 write_ok (cs.own_buf);
4739 else
4740 write_enn (cs.own_buf);
4741 break;
4742 case 'x':
4744 require_running_or_break (cs.own_buf);
4745 decode_x_packet (&cs.own_buf[1], &mem_addr, &len);
4746 int res = gdb_read_memory (mem_addr, mem_buf, len);
4747 if (res < 0)
4748 write_enn (cs.own_buf);
4749 else
4751 gdb_byte *buffer = (gdb_byte *) cs.own_buf;
4752 *buffer++ = 'b';
4754 int out_len_units;
4755 new_packet_len = remote_escape_output (mem_buf, res, 1,
4756 buffer,
4757 &out_len_units,
4758 PBUFSIZ);
4759 new_packet_len++; /* For the 'b' marker. */
4761 if (out_len_units != res)
4763 write_enn (cs.own_buf);
4764 new_packet_len = -1;
4766 else
4767 suppress_next_putpkt_log ();
4770 break;
4771 case 'X':
4772 require_running_or_break (cs.own_buf);
4773 if (decode_X_packet (&cs.own_buf[1], packet_len - 1,
4774 &mem_addr, &len, &mem_buf) < 0
4775 || gdb_write_memory (mem_addr, mem_buf, len) != 0)
4776 write_enn (cs.own_buf);
4777 else
4778 write_ok (cs.own_buf);
4779 break;
4780 case 'C':
4781 require_running_or_break (cs.own_buf);
4782 hex2bin (cs.own_buf + 1, &sig, 1);
4783 if (gdb_signal_to_host_p ((enum gdb_signal) sig))
4784 signal = gdb_signal_to_host ((enum gdb_signal) sig);
4785 else
4786 signal = 0;
4787 myresume (cs.own_buf, 0, signal);
4788 break;
4789 case 'S':
4790 require_running_or_break (cs.own_buf);
4791 hex2bin (cs.own_buf + 1, &sig, 1);
4792 if (gdb_signal_to_host_p ((enum gdb_signal) sig))
4793 signal = gdb_signal_to_host ((enum gdb_signal) sig);
4794 else
4795 signal = 0;
4796 myresume (cs.own_buf, 1, signal);
4797 break;
4798 case 'c':
4799 require_running_or_break (cs.own_buf);
4800 signal = 0;
4801 myresume (cs.own_buf, 0, signal);
4802 break;
4803 case 's':
4804 require_running_or_break (cs.own_buf);
4805 signal = 0;
4806 myresume (cs.own_buf, 1, signal);
4807 break;
4808 case 'Z': /* insert_ ... */
4809 /* Fallthrough. */
4810 case 'z': /* remove_ ... */
4812 char *dataptr;
4813 ULONGEST addr;
4814 int kind;
4815 char type = cs.own_buf[1];
4816 int res;
4817 const int insert = ch == 'Z';
4818 const char *p = &cs.own_buf[3];
4820 p = unpack_varlen_hex (p, &addr);
4821 kind = strtol (p + 1, &dataptr, 16);
4823 if (insert)
4825 struct gdb_breakpoint *bp;
4827 bp = set_gdb_breakpoint (type, addr, kind, &res);
4828 if (bp != NULL)
4830 res = 0;
4832 /* GDB may have sent us a list of *point parameters to
4833 be evaluated on the target's side. Read such list
4834 here. If we already have a list of parameters, GDB
4835 is telling us to drop that list and use this one
4836 instead. */
4837 clear_breakpoint_conditions_and_commands (bp);
4838 const char *options = dataptr;
4839 process_point_options (bp, &options);
4842 else
4843 res = delete_gdb_breakpoint (type, addr, kind);
4845 if (res == 0)
4846 write_ok (cs.own_buf);
4847 else if (res == 1)
4848 /* Unsupported. */
4849 cs.own_buf[0] = '\0';
4850 else
4851 write_enn (cs.own_buf);
4852 break;
4854 case 'k':
4855 response_needed = false;
4856 if (!target_running ())
4857 /* The packet we received doesn't make sense - but we can't
4858 reply to it, either. */
4859 return 0;
4861 fprintf (stderr, "Killing all inferiors\n");
4863 for_each_process (kill_inferior_callback);
4865 /* When using the extended protocol, we wait with no program
4866 running. The traditional protocol will exit instead. */
4867 if (extended_protocol)
4869 cs.last_status.set_exited (GDB_SIGNAL_KILL);
4870 return 0;
4872 else
4873 exit (0);
4875 case 'T':
4877 require_running_or_break (cs.own_buf);
4879 ptid_t thread_id = read_ptid (&cs.own_buf[1], NULL);
4880 if (find_thread_ptid (thread_id) == NULL)
4882 write_enn (cs.own_buf);
4883 break;
4886 if (mythread_alive (thread_id))
4887 write_ok (cs.own_buf);
4888 else
4889 write_enn (cs.own_buf);
4891 break;
4892 case 'R':
4893 response_needed = false;
4895 /* Restarting the inferior is only supported in the extended
4896 protocol. */
4897 if (extended_protocol)
4899 if (target_running ())
4900 for_each_process (kill_inferior_callback);
4902 fprintf (stderr, "GDBserver restarting\n");
4904 /* Wait till we are at 1st instruction in prog. */
4905 if (program_path.get () != NULL)
4907 target_create_inferior (program_path.get (), program_args);
4909 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
4911 /* Stopped at the first instruction of the target
4912 process. */
4913 cs.general_thread = cs.last_ptid;
4915 else
4917 /* Something went wrong. */
4918 cs.general_thread = null_ptid;
4921 else
4923 cs.last_status.set_exited (GDB_SIGNAL_KILL);
4925 return 0;
4927 else
4929 /* It is a request we don't understand. Respond with an
4930 empty packet so that gdb knows that we don't support this
4931 request. */
4932 cs.own_buf[0] = '\0';
4933 break;
4935 case 'v':
4936 /* Extended (long) request. */
4937 handle_v_requests (cs.own_buf, packet_len, &new_packet_len);
4938 break;
4940 default:
4941 /* It is a request we don't understand. Respond with an empty
4942 packet so that gdb knows that we don't support this
4943 request. */
4944 cs.own_buf[0] = '\0';
4945 break;
4948 if (new_packet_len != -1)
4949 putpkt_binary (cs.own_buf, new_packet_len);
4950 else
4951 putpkt (cs.own_buf);
4953 response_needed = false;
4955 if (exit_requested)
4956 return -1;
4958 return 0;
4961 /* Event-loop callback for serial events. */
4963 void
4964 handle_serial_event (int err, gdb_client_data client_data)
4966 threads_debug_printf ("handling possible serial event");
4968 /* Really handle it. */
4969 if (process_serial_event () < 0)
4971 keep_processing_events = false;
4972 return;
4975 /* Be sure to not change the selected thread behind GDB's back.
4976 Important in the non-stop mode asynchronous protocol. */
4977 set_desired_thread ();
4980 /* Push a stop notification on the notification queue. */
4982 static void
4983 push_stop_notification (ptid_t ptid, const target_waitstatus &status)
4985 struct vstop_notif *vstop_notif = new struct vstop_notif;
4987 vstop_notif->status = status;
4988 vstop_notif->ptid = ptid;
4989 /* Push Stop notification. */
4990 notif_push (&notif_stop, vstop_notif);
4993 /* Event-loop callback for target events. */
4995 void
4996 handle_target_event (int err, gdb_client_data client_data)
4998 client_state &cs = get_client_state ();
4999 threads_debug_printf ("handling possible target event");
5001 cs.last_ptid = mywait (minus_one_ptid, &cs.last_status,
5002 TARGET_WNOHANG, 1);
5004 if (cs.last_status.kind () == TARGET_WAITKIND_NO_RESUMED)
5006 if (gdb_connected () && report_no_resumed)
5007 push_stop_notification (null_ptid, cs.last_status);
5009 else if (cs.last_status.kind () != TARGET_WAITKIND_IGNORE)
5011 int pid = cs.last_ptid.pid ();
5012 struct process_info *process = find_process_pid (pid);
5013 int forward_event = !gdb_connected () || process->gdb_detached;
5015 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
5016 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
5018 mark_breakpoints_out (process);
5019 target_mourn_inferior (cs.last_ptid);
5021 else if (cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED)
5023 else
5025 /* We're reporting this thread as stopped. Update its
5026 "want-stopped" state to what the client wants, until it
5027 gets a new resume action. */
5028 current_thread->last_resume_kind = resume_stop;
5029 current_thread->last_status = cs.last_status;
5032 if (forward_event)
5034 if (!target_running ())
5036 /* The last process exited. We're done. */
5037 exit (0);
5040 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
5041 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED
5042 || cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED)
5044 else
5046 /* A thread stopped with a signal, but gdb isn't
5047 connected to handle it. Pass it down to the
5048 inferior, as if it wasn't being traced. */
5049 enum gdb_signal signal;
5051 threads_debug_printf ("GDB not connected; forwarding event %d for"
5052 " [%s]",
5053 (int) cs.last_status.kind (),
5054 target_pid_to_str (cs.last_ptid).c_str ());
5056 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
5057 signal = cs.last_status.sig ();
5058 else
5059 signal = GDB_SIGNAL_0;
5060 target_continue (cs.last_ptid, signal);
5063 else
5065 push_stop_notification (cs.last_ptid, cs.last_status);
5067 if (cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED
5068 && !target_any_resumed ())
5070 target_waitstatus ws;
5071 ws.set_no_resumed ();
5072 push_stop_notification (null_ptid, ws);
5077 /* Be sure to not change the selected thread behind GDB's back.
5078 Important in the non-stop mode asynchronous protocol. */
5079 set_desired_thread ();
5082 /* See gdbsupport/event-loop.h. */
5085 invoke_async_signal_handlers ()
5087 return 0;
5090 /* See gdbsupport/event-loop.h. */
5093 check_async_event_handlers ()
5095 return 0;
5098 /* See gdbsupport/errors.h */
5100 void
5101 flush_streams ()
5103 fflush (stdout);
5104 fflush (stderr);
5107 /* See gdbsupport/gdb_select.h. */
5110 gdb_select (int n, fd_set *readfds, fd_set *writefds,
5111 fd_set *exceptfds, struct timeval *timeout)
5113 return select (n, readfds, writefds, exceptfds, timeout);
5116 #if GDB_SELF_TEST
5117 namespace selftests
5120 void
5121 reset ()
5124 } // namespace selftests
5125 #endif /* GDB_SELF_TEST */