ld: Move the .note.build-id section to near the start of the memory map.
[binutils-gdb.git] / gdbserver / server.cc
blobee537760cfe21552ad9eb5062726dd1f93dc5cdf
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;
124 static std::vector<char *> program_args;
125 static std::string wrapper_argv;
127 /* The PID of the originally created or attached inferior. Used to
128 send signals to the process when GDB sends us an asynchronous interrupt
129 (user hitting Control-C in the client), and to wait for the child to exit
130 when no longer debugging it. */
132 unsigned long signal_pid;
134 /* Set if you want to disable optional thread related packets support
135 in gdbserver, for the sake of testing GDB against stubs that don't
136 support them. */
137 bool disable_packet_vCont;
138 bool disable_packet_Tthread;
139 bool disable_packet_qC;
140 bool disable_packet_qfThreadInfo;
141 bool disable_packet_T;
143 static unsigned char *mem_buf;
145 /* A sub-class of 'struct notif_event' for stop, holding information
146 relative to a single stop reply. We keep a queue of these to
147 push to GDB in non-stop mode. */
149 struct vstop_notif : public notif_event
151 /* Thread or process that got the event. */
152 ptid_t ptid;
154 /* Event info. */
155 struct target_waitstatus status;
158 /* The current btrace configuration. This is gdbserver's mirror of GDB's
159 btrace configuration. */
160 static struct btrace_config current_btrace_conf;
162 /* The client remote protocol state. */
164 static client_state g_client_state;
166 client_state &
167 get_client_state ()
169 client_state &cs = g_client_state;
170 return cs;
174 /* Put a stop reply to the stop reply queue. */
176 static void
177 queue_stop_reply (ptid_t ptid, const target_waitstatus &status)
179 struct vstop_notif *new_notif = new struct vstop_notif;
181 new_notif->ptid = ptid;
182 new_notif->status = status;
184 notif_event_enque (&notif_stop, new_notif);
187 static bool
188 remove_all_on_match_ptid (struct notif_event *event, ptid_t filter_ptid)
190 struct vstop_notif *vstop_event = (struct vstop_notif *) event;
192 return vstop_event->ptid.matches (filter_ptid);
195 /* See server.h. */
197 void
198 discard_queued_stop_replies (ptid_t ptid)
200 std::list<notif_event *>::iterator iter, next, end;
201 end = notif_stop.queue.end ();
202 for (iter = notif_stop.queue.begin (); iter != end; iter = next)
204 next = iter;
205 ++next;
207 if (iter == notif_stop.queue.begin ())
209 /* The head of the list contains the notification that was
210 already sent to GDB. So we can't remove it, otherwise
211 when GDB sends the vStopped, it would ack the _next_
212 notification, which hadn't been sent yet! */
213 continue;
216 if (remove_all_on_match_ptid (*iter, ptid))
218 delete *iter;
219 notif_stop.queue.erase (iter);
224 static void
225 vstop_notif_reply (struct notif_event *event, char *own_buf)
227 struct vstop_notif *vstop = (struct vstop_notif *) event;
229 prepare_resume_reply (own_buf, vstop->ptid, vstop->status);
232 /* Helper for in_queued_stop_replies. */
234 static bool
235 in_queued_stop_replies_ptid (struct notif_event *event, ptid_t filter_ptid)
237 struct vstop_notif *vstop_event = (struct vstop_notif *) event;
239 if (vstop_event->ptid.matches (filter_ptid))
240 return true;
242 /* Don't resume fork children that GDB does not know about yet. */
243 if ((vstop_event->status.kind () == TARGET_WAITKIND_FORKED
244 || vstop_event->status.kind () == TARGET_WAITKIND_VFORKED
245 || vstop_event->status.kind () == TARGET_WAITKIND_THREAD_CLONED)
246 && vstop_event->status.child_ptid ().matches (filter_ptid))
247 return true;
249 return false;
252 /* See server.h. */
255 in_queued_stop_replies (ptid_t ptid)
257 for (notif_event *event : notif_stop.queue)
259 if (in_queued_stop_replies_ptid (event, ptid))
260 return true;
263 return false;
266 struct notif_server notif_stop =
268 "vStopped", "Stop", {}, vstop_notif_reply,
271 static int
272 target_running (void)
274 return get_first_thread () != NULL;
277 /* See gdbsupport/common-inferior.h. */
279 const char *
280 get_exec_wrapper ()
282 return !wrapper_argv.empty () ? wrapper_argv.c_str () : NULL;
285 /* See server.h. */
287 gdb_environ *
288 get_environ ()
290 return &our_environ;
293 static int
294 attach_inferior (int pid)
296 client_state &cs = get_client_state ();
297 /* myattach should return -1 if attaching is unsupported,
298 0 if it succeeded, and call error() otherwise. */
300 if (find_process_pid (pid) != nullptr)
301 error ("Already attached to process %d\n", pid);
303 if (myattach (pid) != 0)
304 return -1;
306 fprintf (stderr, "Attached; pid = %d\n", pid);
307 fflush (stderr);
309 /* FIXME - It may be that we should get the SIGNAL_PID from the
310 attach function, so that it can be the main thread instead of
311 whichever we were told to attach to. */
312 signal_pid = pid;
314 if (!non_stop)
316 cs.last_ptid = mywait (ptid_t (pid), &cs.last_status, 0, 0);
318 /* GDB knows to ignore the first SIGSTOP after attaching to a running
319 process using the "attach" command, but this is different; it's
320 just using "target remote". Pretend it's just starting up. */
321 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED
322 && cs.last_status.sig () == GDB_SIGNAL_STOP)
323 cs.last_status.set_stopped (GDB_SIGNAL_TRAP);
325 current_thread->last_resume_kind = resume_stop;
326 current_thread->last_status = cs.last_status;
329 return 0;
332 /* Decode a qXfer read request. Return 0 if everything looks OK,
333 or -1 otherwise. */
335 static int
336 decode_xfer_read (char *buf, CORE_ADDR *ofs, unsigned int *len)
338 /* After the read marker and annex, qXfer looks like a
339 traditional 'm' packet. */
340 decode_m_packet (buf, ofs, len);
342 return 0;
345 static int
346 decode_xfer (char *buf, char **object, char **rw, char **annex, char **offset)
348 /* Extract and NUL-terminate the object. */
349 *object = buf;
350 while (*buf && *buf != ':')
351 buf++;
352 if (*buf == '\0')
353 return -1;
354 *buf++ = 0;
356 /* Extract and NUL-terminate the read/write action. */
357 *rw = buf;
358 while (*buf && *buf != ':')
359 buf++;
360 if (*buf == '\0')
361 return -1;
362 *buf++ = 0;
364 /* Extract and NUL-terminate the annex. */
365 *annex = buf;
366 while (*buf && *buf != ':')
367 buf++;
368 if (*buf == '\0')
369 return -1;
370 *buf++ = 0;
372 *offset = buf;
373 return 0;
376 /* Write the response to a successful qXfer read. Returns the
377 length of the (binary) data stored in BUF, corresponding
378 to as much of DATA/LEN as we could fit. IS_MORE controls
379 the first character of the response. */
380 static int
381 write_qxfer_response (char *buf, const gdb_byte *data, int len, int is_more)
383 int out_len;
385 if (is_more)
386 buf[0] = 'm';
387 else
388 buf[0] = 'l';
390 return remote_escape_output (data, len, 1, (unsigned char *) buf + 1,
391 &out_len, PBUFSIZ - 2) + 1;
394 /* Handle btrace enabling in BTS format. */
396 static void
397 handle_btrace_enable_bts (struct thread_info *thread)
399 if (thread->btrace != NULL)
400 error (_("Btrace already enabled."));
402 current_btrace_conf.format = BTRACE_FORMAT_BTS;
403 thread->btrace = target_enable_btrace (thread, &current_btrace_conf);
406 /* Handle btrace enabling in Intel Processor Trace format. */
408 static void
409 handle_btrace_enable_pt (struct thread_info *thread)
411 if (thread->btrace != NULL)
412 error (_("Btrace already enabled."));
414 current_btrace_conf.format = BTRACE_FORMAT_PT;
415 thread->btrace = target_enable_btrace (thread, &current_btrace_conf);
418 /* Handle btrace disabling. */
420 static void
421 handle_btrace_disable (struct thread_info *thread)
424 if (thread->btrace == NULL)
425 error (_("Branch tracing not enabled."));
427 if (target_disable_btrace (thread->btrace) != 0)
428 error (_("Could not disable branch tracing."));
430 thread->btrace = NULL;
433 /* Handle the "Qbtrace" packet. */
435 static int
436 handle_btrace_general_set (char *own_buf)
438 client_state &cs = get_client_state ();
439 struct thread_info *thread;
440 char *op;
442 if (!startswith (own_buf, "Qbtrace:"))
443 return 0;
445 op = own_buf + strlen ("Qbtrace:");
447 if (cs.general_thread == null_ptid
448 || cs.general_thread == minus_one_ptid)
450 strcpy (own_buf, "E.Must select a single thread.");
451 return -1;
454 thread = find_thread_ptid (cs.general_thread);
455 if (thread == NULL)
457 strcpy (own_buf, "E.No such thread.");
458 return -1;
463 if (strcmp (op, "bts") == 0)
464 handle_btrace_enable_bts (thread);
465 else if (strcmp (op, "pt") == 0)
466 handle_btrace_enable_pt (thread);
467 else if (strcmp (op, "off") == 0)
468 handle_btrace_disable (thread);
469 else
470 error (_("Bad Qbtrace operation. Use bts, pt, or off."));
472 write_ok (own_buf);
474 catch (const gdb_exception_error &exception)
476 sprintf (own_buf, "E.%s", exception.what ());
479 return 1;
482 /* Handle the "Qbtrace-conf" packet. */
484 static int
485 handle_btrace_conf_general_set (char *own_buf)
487 client_state &cs = get_client_state ();
488 struct thread_info *thread;
489 char *op;
491 if (!startswith (own_buf, "Qbtrace-conf:"))
492 return 0;
494 op = own_buf + strlen ("Qbtrace-conf:");
496 if (cs.general_thread == null_ptid
497 || cs.general_thread == minus_one_ptid)
499 strcpy (own_buf, "E.Must select a single thread.");
500 return -1;
503 thread = find_thread_ptid (cs.general_thread);
504 if (thread == NULL)
506 strcpy (own_buf, "E.No such thread.");
507 return -1;
510 if (startswith (op, "bts:size="))
512 unsigned long size;
513 char *endp = NULL;
515 errno = 0;
516 size = strtoul (op + strlen ("bts:size="), &endp, 16);
517 if (endp == NULL || *endp != 0 || errno != 0 || size > UINT_MAX)
519 strcpy (own_buf, "E.Bad size value.");
520 return -1;
523 current_btrace_conf.bts.size = (unsigned int) size;
525 else if (strncmp (op, "pt:size=", strlen ("pt:size=")) == 0)
527 unsigned long size;
528 char *endp = NULL;
530 errno = 0;
531 size = strtoul (op + strlen ("pt:size="), &endp, 16);
532 if (endp == NULL || *endp != 0 || errno != 0 || size > UINT_MAX)
534 strcpy (own_buf, "E.Bad size value.");
535 return -1;
538 current_btrace_conf.pt.size = (unsigned int) size;
540 else if (strncmp (op, "pt:ptwrite=", strlen ("pt:ptwrite=")) == 0)
542 op += strlen ("pt:ptwrite=");
543 if (strncmp (op, "\"yes\"", strlen ("\"yes\"")) == 0)
544 current_btrace_conf.pt.ptwrite = true;
545 else if (strncmp (op, "\"no\"", strlen ("\"no\"")) == 0)
546 current_btrace_conf.pt.ptwrite = false;
547 else
549 strcpy (own_buf, "E.Bad ptwrite value.");
550 return -1;
553 else
555 strcpy (own_buf, "E.Bad Qbtrace configuration option.");
556 return -1;
559 write_ok (own_buf);
560 return 1;
563 /* Create the qMemTags packet reply given TAGS.
565 Returns true if parsing succeeded and false otherwise. */
567 static bool
568 create_fetch_memtags_reply (char *reply, const gdb::byte_vector &tags)
570 /* It is an error to pass a zero-sized tag vector. */
571 gdb_assert (tags.size () != 0);
573 std::string packet ("m");
575 /* Write the tag data. */
576 packet += bin2hex (tags.data (), tags.size ());
578 /* Check if the reply is too big for the packet to handle. */
579 if (PBUFSIZ < packet.size ())
580 return false;
582 strcpy (reply, packet.c_str ());
583 return true;
586 /* Parse the QMemTags request into ADDR, LEN and TAGS.
588 Returns true if parsing succeeded and false otherwise. */
590 static bool
591 parse_store_memtags_request (char *request, CORE_ADDR *addr, size_t *len,
592 gdb::byte_vector &tags, int *type)
594 gdb_assert (startswith (request, "QMemTags:"));
596 const char *p = request + strlen ("QMemTags:");
598 /* Read address and length. */
599 unsigned int length = 0;
600 p = decode_m_packet_params (p, addr, &length, ':');
601 *len = length;
603 /* Read the tag type. */
604 ULONGEST tag_type = 0;
605 p = unpack_varlen_hex (p, &tag_type);
606 *type = (int) tag_type;
608 /* Make sure there is a colon after the type. */
609 if (*p != ':')
610 return false;
612 /* Skip the colon. */
613 p++;
615 /* Read the tag data. */
616 tags = hex2bin (p);
618 return true;
621 /* Parse thread options starting at *P and return them. On exit,
622 advance *P past the options. */
624 static gdb_thread_options
625 parse_gdb_thread_options (const char **p)
627 ULONGEST options = 0;
628 *p = unpack_varlen_hex (*p, &options);
629 return (gdb_thread_option) options;
632 /* Handle all of the extended 'Q' packets. */
634 static void
635 handle_general_set (char *own_buf)
637 client_state &cs = get_client_state ();
638 if (startswith (own_buf, "QPassSignals:"))
640 int numsigs = (int) GDB_SIGNAL_LAST, i;
641 const char *p = own_buf + strlen ("QPassSignals:");
642 CORE_ADDR cursig;
644 p = decode_address_to_semicolon (&cursig, p);
645 for (i = 0; i < numsigs; i++)
647 if (i == cursig)
649 cs.pass_signals[i] = 1;
650 if (*p == '\0')
651 /* Keep looping, to clear the remaining signals. */
652 cursig = -1;
653 else
654 p = decode_address_to_semicolon (&cursig, p);
656 else
657 cs.pass_signals[i] = 0;
659 strcpy (own_buf, "OK");
660 return;
663 if (startswith (own_buf, "QProgramSignals:"))
665 int numsigs = (int) GDB_SIGNAL_LAST, i;
666 const char *p = own_buf + strlen ("QProgramSignals:");
667 CORE_ADDR cursig;
669 cs.program_signals_p = 1;
671 p = decode_address_to_semicolon (&cursig, p);
672 for (i = 0; i < numsigs; i++)
674 if (i == cursig)
676 cs.program_signals[i] = 1;
677 if (*p == '\0')
678 /* Keep looping, to clear the remaining signals. */
679 cursig = -1;
680 else
681 p = decode_address_to_semicolon (&cursig, p);
683 else
684 cs.program_signals[i] = 0;
686 strcpy (own_buf, "OK");
687 return;
690 if (startswith (own_buf, "QCatchSyscalls:"))
692 const char *p = own_buf + sizeof ("QCatchSyscalls:") - 1;
693 int enabled = -1;
694 CORE_ADDR sysno;
695 struct process_info *process;
697 if (!target_running () || !target_supports_catch_syscall ())
699 write_enn (own_buf);
700 return;
703 if (strcmp (p, "0") == 0)
704 enabled = 0;
705 else if (p[0] == '1' && (p[1] == ';' || p[1] == '\0'))
706 enabled = 1;
707 else
709 fprintf (stderr, "Unknown catch-syscalls mode requested: %s\n",
710 own_buf);
711 write_enn (own_buf);
712 return;
715 process = current_process ();
716 process->syscalls_to_catch.clear ();
718 if (enabled)
720 p += 1;
721 if (*p == ';')
723 p += 1;
724 while (*p != '\0')
726 p = decode_address_to_semicolon (&sysno, p);
727 process->syscalls_to_catch.push_back (sysno);
730 else
731 process->syscalls_to_catch.push_back (ANY_SYSCALL);
734 write_ok (own_buf);
735 return;
738 if (strcmp (own_buf, "QEnvironmentReset") == 0)
740 our_environ = gdb_environ::from_host_environ ();
742 write_ok (own_buf);
743 return;
746 if (startswith (own_buf, "QEnvironmentHexEncoded:"))
748 const char *p = own_buf + sizeof ("QEnvironmentHexEncoded:") - 1;
749 /* The final form of the environment variable. FINAL_VAR will
750 hold the 'VAR=VALUE' format. */
751 std::string final_var = hex2str (p);
752 std::string var_name, var_value;
754 remote_debug_printf ("[QEnvironmentHexEncoded received '%s']", p);
755 remote_debug_printf ("[Environment variable to be set: '%s']",
756 final_var.c_str ());
758 size_t pos = final_var.find ('=');
759 if (pos == std::string::npos)
761 warning (_("Unexpected format for environment variable: '%s'"),
762 final_var.c_str ());
763 write_enn (own_buf);
764 return;
767 var_name = final_var.substr (0, pos);
768 var_value = final_var.substr (pos + 1, std::string::npos);
770 our_environ.set (var_name.c_str (), var_value.c_str ());
772 write_ok (own_buf);
773 return;
776 if (startswith (own_buf, "QEnvironmentUnset:"))
778 const char *p = own_buf + sizeof ("QEnvironmentUnset:") - 1;
779 std::string varname = hex2str (p);
781 remote_debug_printf ("[QEnvironmentUnset received '%s']", p);
782 remote_debug_printf ("[Environment variable to be unset: '%s']",
783 varname.c_str ());
785 our_environ.unset (varname.c_str ());
787 write_ok (own_buf);
788 return;
791 if (strcmp (own_buf, "QStartNoAckMode") == 0)
793 remote_debug_printf ("[noack mode enabled]");
795 cs.noack_mode = 1;
796 write_ok (own_buf);
797 return;
800 if (startswith (own_buf, "QNonStop:"))
802 char *mode = own_buf + 9;
803 int req = -1;
804 const char *req_str;
806 if (strcmp (mode, "0") == 0)
807 req = 0;
808 else if (strcmp (mode, "1") == 0)
809 req = 1;
810 else
812 /* We don't know what this mode is, so complain to
813 GDB. */
814 fprintf (stderr, "Unknown non-stop mode requested: %s\n",
815 own_buf);
816 write_enn (own_buf);
817 return;
820 req_str = req ? "non-stop" : "all-stop";
821 if (the_target->start_non_stop (req == 1) != 0)
823 fprintf (stderr, "Setting %s mode failed\n", req_str);
824 write_enn (own_buf);
825 return;
828 non_stop = (req != 0);
830 remote_debug_printf ("[%s mode enabled]", req_str);
832 write_ok (own_buf);
833 return;
836 if (startswith (own_buf, "QDisableRandomization:"))
838 char *packet = own_buf + strlen ("QDisableRandomization:");
839 ULONGEST setting;
841 unpack_varlen_hex (packet, &setting);
842 cs.disable_randomization = setting;
844 remote_debug_printf (cs.disable_randomization
845 ? "[address space randomization disabled]"
846 : "[address space randomization enabled]");
848 write_ok (own_buf);
849 return;
852 if (target_supports_tracepoints ()
853 && handle_tracepoint_general_set (own_buf))
854 return;
856 if (startswith (own_buf, "QAgent:"))
858 char *mode = own_buf + strlen ("QAgent:");
859 int req = 0;
861 if (strcmp (mode, "0") == 0)
862 req = 0;
863 else if (strcmp (mode, "1") == 0)
864 req = 1;
865 else
867 /* We don't know what this value is, so complain to GDB. */
868 sprintf (own_buf, "E.Unknown QAgent value");
869 return;
872 /* Update the flag. */
873 use_agent = req;
874 remote_debug_printf ("[%s agent]", req ? "Enable" : "Disable");
875 write_ok (own_buf);
876 return;
879 if (handle_btrace_general_set (own_buf))
880 return;
882 if (handle_btrace_conf_general_set (own_buf))
883 return;
885 if (startswith (own_buf, "QThreadEvents:"))
887 char *mode = own_buf + strlen ("QThreadEvents:");
888 enum tribool req = TRIBOOL_UNKNOWN;
890 if (strcmp (mode, "0") == 0)
891 req = TRIBOOL_FALSE;
892 else if (strcmp (mode, "1") == 0)
893 req = TRIBOOL_TRUE;
894 else
896 /* We don't know what this mode is, so complain to GDB. */
897 std::string err
898 = string_printf ("E.Unknown thread-events mode requested: %s\n",
899 mode);
900 strcpy (own_buf, err.c_str ());
901 return;
904 cs.report_thread_events = (req == TRIBOOL_TRUE);
906 remote_debug_printf ("[thread events are now %s]\n",
907 cs.report_thread_events ? "enabled" : "disabled");
909 write_ok (own_buf);
910 return;
913 if (startswith (own_buf, "QThreadOptions;"))
915 const char *p = own_buf + strlen ("QThreadOptions");
917 gdb_thread_options supported_options = target_supported_thread_options ();
918 if (supported_options == 0)
920 /* Something went wrong -- we don't support any option, but
921 GDB sent the packet anyway. */
922 write_enn (own_buf);
923 return;
926 /* We could store the options directly in thread->thread_options
927 without this map, but that would mean that a QThreadOptions
928 packet with a wildcard like "QThreadOptions;0;3:TID" would
929 result in the debug logs showing:
931 [options for TID are now 0x0]
932 [options for TID are now 0x3]
934 It's nicer if we only print the final options for each TID,
935 and if we only print about it if the options changed compared
936 to the options that were previously set on the thread. */
937 std::unordered_map<thread_info *, gdb_thread_options> set_options;
939 while (*p != '\0')
941 if (p[0] != ';')
943 write_enn (own_buf);
944 return;
946 p++;
948 /* Read the options. */
950 gdb_thread_options options = parse_gdb_thread_options (&p);
952 if ((options & ~supported_options) != 0)
954 /* GDB asked for an unknown or unsupported option, so
955 error out. */
956 std::string err
957 = string_printf ("E.Unknown thread options requested: %s\n",
958 to_string (options).c_str ());
959 strcpy (own_buf, err.c_str ());
960 return;
963 ptid_t ptid;
965 if (p[0] == ';' || p[0] == '\0')
966 ptid = minus_one_ptid;
967 else if (p[0] == ':')
969 const char *q;
971 ptid = read_ptid (p + 1, &q);
973 if (p == q)
975 write_enn (own_buf);
976 return;
978 p = q;
979 if (p[0] != ';' && p[0] != '\0')
981 write_enn (own_buf);
982 return;
985 else
987 write_enn (own_buf);
988 return;
991 /* Convert PID.-1 => PID.0 for ptid.matches. */
992 if (ptid.lwp () == -1)
993 ptid = ptid_t (ptid.pid ());
995 for_each_thread ([&] (thread_info *thread)
997 if (ptid_of (thread).matches (ptid))
998 set_options[thread] = options;
1002 for (const auto &iter : set_options)
1004 thread_info *thread = iter.first;
1005 gdb_thread_options options = iter.second;
1007 if (thread->thread_options != options)
1009 threads_debug_printf ("[options for %s are now %s]\n",
1010 target_pid_to_str (ptid_of (thread)).c_str (),
1011 to_string (options).c_str ());
1013 thread->thread_options = options;
1017 write_ok (own_buf);
1018 return;
1021 if (startswith (own_buf, "QStartupWithShell:"))
1023 const char *value = own_buf + strlen ("QStartupWithShell:");
1025 if (strcmp (value, "1") == 0)
1026 startup_with_shell = true;
1027 else if (strcmp (value, "0") == 0)
1028 startup_with_shell = false;
1029 else
1031 /* Unknown value. */
1032 fprintf (stderr, "Unknown value to startup-with-shell: %s\n",
1033 own_buf);
1034 write_enn (own_buf);
1035 return;
1038 remote_debug_printf ("[Inferior will %s started with shell]",
1039 startup_with_shell ? "be" : "not be");
1041 write_ok (own_buf);
1042 return;
1045 if (startswith (own_buf, "QSetWorkingDir:"))
1047 const char *p = own_buf + strlen ("QSetWorkingDir:");
1049 if (*p != '\0')
1051 std::string path = hex2str (p);
1053 remote_debug_printf ("[Set the inferior's current directory to %s]",
1054 path.c_str ());
1056 set_inferior_cwd (std::move (path));
1058 else
1060 /* An empty argument means that we should clear out any
1061 previously set cwd for the inferior. */
1062 set_inferior_cwd ("");
1064 remote_debug_printf ("[Unset the inferior's current directory; will "
1065 "use gdbserver's cwd]");
1067 write_ok (own_buf);
1069 return;
1073 /* Handle store memory tags packets. */
1074 if (startswith (own_buf, "QMemTags:")
1075 && target_supports_memory_tagging ())
1077 gdb::byte_vector tags;
1078 CORE_ADDR addr = 0;
1079 size_t len = 0;
1080 int type = 0;
1082 require_running_or_return (own_buf);
1084 bool ret = parse_store_memtags_request (own_buf, &addr, &len, tags,
1085 &type);
1087 if (ret)
1088 ret = the_target->store_memtags (addr, len, tags, type);
1090 if (!ret)
1091 write_enn (own_buf);
1092 else
1093 write_ok (own_buf);
1095 return;
1098 /* Otherwise we didn't know what packet it was. Say we didn't
1099 understand it. */
1100 own_buf[0] = 0;
1103 static const char *
1104 get_features_xml (const char *annex)
1106 const struct target_desc *desc = current_target_desc ();
1108 /* `desc->xmltarget' defines what to return when looking for the
1109 "target.xml" file. Its contents can either be verbatim XML code
1110 (prefixed with a '@') or else the name of the actual XML file to
1111 be used in place of "target.xml".
1113 This variable is set up from the auto-generated
1114 init_registers_... routine for the current target. */
1116 if (strcmp (annex, "target.xml") == 0)
1118 const char *ret = tdesc_get_features_xml (desc);
1120 if (*ret == '@')
1121 return ret + 1;
1122 else
1123 annex = ret;
1126 #ifdef USE_XML
1128 int i;
1130 /* Look for the annex. */
1131 for (i = 0; xml_builtin[i][0] != NULL; i++)
1132 if (strcmp (annex, xml_builtin[i][0]) == 0)
1133 break;
1135 if (xml_builtin[i][0] != NULL)
1136 return xml_builtin[i][1];
1138 #endif
1140 return NULL;
1143 static void
1144 monitor_show_help (void)
1146 monitor_output ("The following monitor commands are supported:\n");
1147 monitor_output (" set debug on\n");
1148 monitor_output (" Enable general debugging messages\n");
1149 monitor_output (" set debug off\n");
1150 monitor_output (" Disable all debugging messages\n");
1151 monitor_output (" set debug COMPONENT <off|on>\n");
1152 monitor_output (" Enable debugging messages for COMPONENT, which is\n");
1153 monitor_output (" one of: all, threads, remote, event-loop.\n");
1154 monitor_output (" set debug-hw-points <0|1>\n");
1155 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
1156 monitor_output (" set debug-format option1[,option2,...]\n");
1157 monitor_output (" Add additional information to debugging messages\n");
1158 monitor_output (" Options: all, none, timestamp\n");
1159 monitor_output (" exit\n");
1160 monitor_output (" Quit GDBserver\n");
1163 /* Read trace frame or inferior memory. Returns the number of bytes
1164 actually read, zero when no further transfer is possible, and -1 on
1165 error. Return of a positive value smaller than LEN does not
1166 indicate there's no more to be read, only the end of the transfer.
1167 E.g., when GDB reads memory from a traceframe, a first request may
1168 be served from a memory block that does not cover the whole request
1169 length. A following request gets the rest served from either
1170 another block (of the same traceframe) or from the read-only
1171 regions. */
1173 static int
1174 gdb_read_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
1176 client_state &cs = get_client_state ();
1177 int res;
1179 if (cs.current_traceframe >= 0)
1181 ULONGEST nbytes;
1182 ULONGEST length = len;
1184 if (traceframe_read_mem (cs.current_traceframe,
1185 memaddr, myaddr, len, &nbytes))
1186 return -1;
1187 /* Data read from trace buffer, we're done. */
1188 if (nbytes > 0)
1189 return nbytes;
1190 if (!in_readonly_region (memaddr, length))
1191 return -1;
1192 /* Otherwise we have a valid readonly case, fall through. */
1193 /* (assume no half-trace half-real blocks for now) */
1196 if (set_desired_process ())
1197 res = read_inferior_memory (memaddr, myaddr, len);
1198 else
1199 res = 1;
1201 return res == 0 ? len : -1;
1204 /* Write trace frame or inferior memory. Actually, writing to trace
1205 frames is forbidden. */
1207 static int
1208 gdb_write_memory (CORE_ADDR memaddr, const unsigned char *myaddr, int len)
1210 client_state &cs = get_client_state ();
1211 if (cs.current_traceframe >= 0)
1212 return EIO;
1213 else
1215 int ret;
1217 if (set_desired_process ())
1218 ret = target_write_memory (memaddr, myaddr, len);
1219 else
1220 ret = EIO;
1221 return ret;
1225 /* Handle qSearch:memory packets. */
1227 static void
1228 handle_search_memory (char *own_buf, int packet_len)
1230 CORE_ADDR start_addr;
1231 CORE_ADDR search_space_len;
1232 gdb_byte *pattern;
1233 unsigned int pattern_len;
1234 int found;
1235 CORE_ADDR found_addr;
1236 int cmd_name_len = sizeof ("qSearch:memory:") - 1;
1238 pattern = (gdb_byte *) malloc (packet_len);
1239 if (pattern == NULL)
1240 error ("Unable to allocate memory to perform the search");
1242 if (decode_search_memory_packet (own_buf + cmd_name_len,
1243 packet_len - cmd_name_len,
1244 &start_addr, &search_space_len,
1245 pattern, &pattern_len) < 0)
1247 free (pattern);
1248 error ("Error in parsing qSearch:memory packet");
1251 auto read_memory = [] (CORE_ADDR addr, gdb_byte *result, size_t len)
1253 return gdb_read_memory (addr, result, len) == len;
1256 found = simple_search_memory (read_memory, start_addr, search_space_len,
1257 pattern, pattern_len, &found_addr);
1259 if (found > 0)
1260 sprintf (own_buf, "1,%lx", (long) found_addr);
1261 else if (found == 0)
1262 strcpy (own_buf, "0");
1263 else
1264 strcpy (own_buf, "E00");
1266 free (pattern);
1269 /* Handle the "D" packet. */
1271 static void
1272 handle_detach (char *own_buf)
1274 client_state &cs = get_client_state ();
1276 process_info *process;
1278 if (cs.multi_process)
1280 /* skip 'D;' */
1281 int pid = strtol (&own_buf[2], NULL, 16);
1283 process = find_process_pid (pid);
1285 else
1287 process = (current_thread != nullptr
1288 ? get_thread_process (current_thread)
1289 : nullptr);
1292 if (process == NULL)
1294 write_enn (own_buf);
1295 return;
1298 if ((tracing && disconnected_tracing) || any_persistent_commands (process))
1300 if (tracing && disconnected_tracing)
1301 fprintf (stderr,
1302 "Disconnected tracing in effect, "
1303 "leaving gdbserver attached to the process\n");
1305 if (any_persistent_commands (process))
1306 fprintf (stderr,
1307 "Persistent commands are present, "
1308 "leaving gdbserver attached to the process\n");
1310 /* Make sure we're in non-stop/async mode, so we we can both
1311 wait for an async socket accept, and handle async target
1312 events simultaneously. There's also no point either in
1313 having the target stop all threads, when we're going to
1314 pass signals down without informing GDB. */
1315 if (!non_stop)
1317 threads_debug_printf ("Forcing non-stop mode");
1319 non_stop = true;
1320 the_target->start_non_stop (true);
1323 process->gdb_detached = 1;
1325 /* Detaching implicitly resumes all threads. */
1326 target_continue_no_signal (minus_one_ptid);
1328 write_ok (own_buf);
1329 return;
1332 fprintf (stderr, "Detaching from process %d\n", process->pid);
1333 stop_tracing ();
1335 /* We'll need this after PROCESS has been destroyed. */
1336 int pid = process->pid;
1338 /* If this process has an unreported fork child, that child is not known to
1339 GDB, so GDB won't take care of detaching it. We must do it here.
1341 Here, we specifically don't want to use "safe iteration", as detaching
1342 another process might delete the next thread in the iteration, which is
1343 the one saved by the safe iterator. We will never delete the currently
1344 iterated on thread, so standard iteration should be safe. */
1345 for (thread_info *thread : all_threads)
1347 /* Only threads that are of the process we are detaching. */
1348 if (thread->id.pid () != pid)
1349 continue;
1351 /* Only threads that have a pending fork event. */
1352 target_waitkind kind;
1353 thread_info *child = target_thread_pending_child (thread, &kind);
1354 if (child == nullptr || kind == TARGET_WAITKIND_THREAD_CLONED)
1355 continue;
1357 process_info *fork_child_process = get_thread_process (child);
1358 gdb_assert (fork_child_process != nullptr);
1360 int fork_child_pid = fork_child_process->pid;
1362 if (detach_inferior (fork_child_process) != 0)
1363 warning (_("Failed to detach fork child %s, child of %s"),
1364 target_pid_to_str (ptid_t (fork_child_pid)).c_str (),
1365 target_pid_to_str (thread->id).c_str ());
1368 if (detach_inferior (process) != 0)
1369 write_enn (own_buf);
1370 else
1372 discard_queued_stop_replies (ptid_t (pid));
1373 write_ok (own_buf);
1375 if (extended_protocol || target_running ())
1377 /* There is still at least one inferior remaining or
1378 we are in extended mode, so don't terminate gdbserver,
1379 and instead treat this like a normal program exit. */
1380 cs.last_status.set_exited (0);
1381 cs.last_ptid = ptid_t (pid);
1383 switch_to_thread (nullptr);
1385 else
1387 putpkt (own_buf);
1388 remote_close ();
1390 /* If we are attached, then we can exit. Otherwise, we
1391 need to hang around doing nothing, until the child is
1392 gone. */
1393 join_inferior (pid);
1394 exit (0);
1399 /* Parse options to --debug-format= and "monitor set debug-format".
1400 ARG is the text after "--debug-format=" or "monitor set debug-format".
1401 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1402 This triggers calls to monitor_output.
1403 The result is an empty string if all options were parsed ok, otherwise an
1404 error message which the caller must free.
1406 N.B. These commands affect all debug format settings, they are not
1407 cumulative. If a format is not specified, it is turned off.
1408 However, we don't go to extra trouble with things like
1409 "monitor set debug-format all,none,timestamp".
1410 Instead we just parse them one at a time, in order.
1412 The syntax for "monitor set debug" we support here is not identical
1413 to gdb's "set debug foo on|off" because we also use this function to
1414 parse "--debug-format=foo,bar". */
1416 static std::string
1417 parse_debug_format_options (const char *arg, int is_monitor)
1419 /* First turn all debug format options off. */
1420 debug_timestamp = 0;
1422 /* First remove leading spaces, for "monitor set debug-format". */
1423 while (isspace (*arg))
1424 ++arg;
1426 std::vector<gdb::unique_xmalloc_ptr<char>> options
1427 = delim_string_to_char_ptr_vec (arg, ',');
1429 for (const gdb::unique_xmalloc_ptr<char> &option : options)
1431 if (strcmp (option.get (), "all") == 0)
1433 debug_timestamp = 1;
1434 if (is_monitor)
1435 monitor_output ("All extra debug format options enabled.\n");
1437 else if (strcmp (option.get (), "none") == 0)
1439 debug_timestamp = 0;
1440 if (is_monitor)
1441 monitor_output ("All extra debug format options disabled.\n");
1443 else if (strcmp (option.get (), "timestamp") == 0)
1445 debug_timestamp = 1;
1446 if (is_monitor)
1447 monitor_output ("Timestamps will be added to debug output.\n");
1449 else if (*option == '\0')
1451 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1452 continue;
1454 else
1455 return string_printf ("Unknown debug-format argument: \"%s\"\n",
1456 option.get ());
1459 return std::string ();
1462 /* A wrapper to enable, or disable a debug flag. These are debug flags
1463 that control the debug output from gdbserver, that developers might
1464 want, this is not something most end users will need. */
1466 struct debug_opt
1468 /* NAME is the name of this debug option, this should be a simple string
1469 containing no whitespace, starting with a letter from isalpha(), and
1470 contain only isalnum() characters and '_' underscore and '-' hyphen.
1472 SETTER is a callback function used to set the debug variable. This
1473 callback will be passed true to enable the debug setting, or false to
1474 disable the debug setting. */
1475 debug_opt (const char *name, std::function<void (bool)> setter)
1476 : m_name (name),
1477 m_setter (setter)
1479 gdb_assert (isalpha (*name));
1482 /* Called to enable or disable the debug setting. */
1483 void set (bool enable) const
1485 m_setter (enable);
1488 /* Return the name of this debug option. */
1489 const char *name () const
1490 { return m_name; }
1492 private:
1493 /* The name of this debug option. */
1494 const char *m_name;
1496 /* The callback to update the debug setting. */
1497 std::function<void (bool)> m_setter;
1500 /* The set of all debug options that gdbserver supports. These are the
1501 options that can be passed to the command line '--debug=...' flag, or to
1502 the monitor command 'monitor set debug ...'. */
1504 static std::vector<debug_opt> all_debug_opt {
1505 {"threads", [] (bool enable)
1507 debug_threads = enable;
1509 {"remote", [] (bool enable)
1511 remote_debug = enable;
1513 {"event-loop", [] (bool enable)
1515 debug_event_loop = (enable ? debug_event_loop_kind::ALL
1516 : debug_event_loop_kind::OFF);
1520 /* Parse the options to --debug=...
1522 OPTIONS is the string of debug components which should be enabled (or
1523 disabled), and must not be nullptr. An empty OPTIONS string is valid,
1524 in which case a default set of debug components will be enabled.
1526 An unknown, or otherwise invalid debug component will result in an
1527 exception being thrown.
1529 OPTIONS can consist of multiple debug component names separated by a
1530 comma. Debugging for each component will be turned on. The special
1531 component 'all' can be used to enable debugging for all components.
1533 A component can also be prefixed with '-' to disable debugging of that
1534 component, so a user might use: '--debug=all,-remote', to enable all
1535 debugging, except for the remote (protocol) component. Components are
1536 processed left to write in the OPTIONS list. */
1538 static void
1539 parse_debug_options (const char *options)
1541 gdb_assert (options != nullptr);
1543 /* Empty options means the "default" set. This exists mostly for
1544 backwards compatibility with gdbserver's legacy behaviour. */
1545 if (*options == '\0')
1546 options = "+threads";
1548 while (*options != '\0')
1550 const char *end = strchrnul (options, ',');
1552 bool enable = *options != '-';
1553 if (*options == '-' || *options == '+')
1554 ++options;
1556 std::string opt (options, end - options);
1558 if (opt.size () == 0)
1559 error ("invalid empty debug option");
1561 bool is_opt_all = opt == "all";
1563 bool found = false;
1564 for (const auto &debug_opt : all_debug_opt)
1565 if (is_opt_all || opt == debug_opt.name ())
1567 debug_opt.set (enable);
1568 found = true;
1569 if (!is_opt_all)
1570 break;
1573 if (!found)
1574 error ("unknown debug option '%s'", opt.c_str ());
1576 options = (*end == ',') ? end + 1 : end;
1580 /* Called from the 'monitor' command handler, to handle general 'set debug'
1581 monitor commands with one of the formats:
1583 set debug COMPONENT VALUE
1584 set debug VALUE
1586 In both of these command formats VALUE can be 'on', 'off', '1', or '0'
1587 with 1/0 being equivalent to on/off respectively.
1589 In the no-COMPONENT version of the command, if VALUE is 'on' (or '1')
1590 then the component 'threads' is assumed, this is for backward
1591 compatibility, but maybe in the future we might find a better "default"
1592 set of debug flags to enable.
1594 In the no-COMPONENT version of the command, if VALUE is 'off' (or '0')
1595 then all debugging is turned off.
1597 Otherwise, COMPONENT must be one of the known debug components, and that
1598 component is either enabled or disabled as appropriate.
1600 The string MON contains either 'COMPONENT VALUE' or just the 'VALUE' for
1601 the second command format, the 'set debug ' has been stripped off
1602 already.
1604 Return a string containing an error message if something goes wrong,
1605 this error can be returned as part of the monitor command output. If
1606 everything goes correctly then the debug global will have been updated,
1607 and an empty string is returned. */
1609 static std::string
1610 handle_general_monitor_debug (const char *mon)
1612 mon = skip_spaces (mon);
1614 if (*mon == '\0')
1615 return "No debug component name found.\n";
1617 /* Find the first word within MON. This is either the component name,
1618 or the value if no component has been given. */
1619 const char *end = skip_to_space (mon);
1620 std::string component (mon, end - mon);
1621 if (component.find (',') != component.npos || component[0] == '-'
1622 || component[0] == '+')
1623 return "Invalid character found in debug component name.\n";
1625 /* In ACTION_STR we create a string that will be passed to the
1626 parse_debug_options string. This will be either '+COMPONENT' or
1627 '-COMPONENT' depending on whether we want to enable or disable
1628 COMPONENT. */
1629 std::string action_str;
1631 /* If parse_debug_options succeeds, then MSG will be returned to the user
1632 as the output of the monitor command. */
1633 std::string msg;
1635 /* Check for 'set debug off', this disables all debug output. */
1636 if (component == "0" || component == "off")
1638 if (*skip_spaces (end) != '\0')
1639 return string_printf
1640 ("Junk '%s' found at end of 'set debug %s' command.\n",
1641 skip_spaces (end), std::string (mon, end - mon).c_str ());
1643 action_str = "-all";
1644 msg = "All debug output disabled.\n";
1646 /* Check for 'set debug on', this disables a general set of debug. */
1647 else if (component == "1" || component == "on")
1649 if (*skip_spaces (end) != '\0')
1650 return string_printf
1651 ("Junk '%s' found at end of 'set debug %s' command.\n",
1652 skip_spaces (end), std::string (mon, end - mon).c_str ());
1654 action_str = "+threads";
1655 msg = "General debug output enabled.\n";
1657 /* Otherwise we should have 'set debug COMPONENT VALUE'. Extract the two
1658 parts and validate. */
1659 else
1661 /* Figure out the value the user passed. */
1662 const char *value_start = skip_spaces (end);
1663 if (*value_start == '\0')
1664 return string_printf ("Missing value for 'set debug %s' command.\n",
1665 mon);
1667 const char *after_value = skip_to_space (value_start);
1668 if (*skip_spaces (after_value) != '\0')
1669 return string_printf
1670 ("Junk '%s' found at end of 'set debug %s' command.\n",
1671 skip_spaces (after_value),
1672 std::string (mon, after_value - mon).c_str ());
1674 std::string value (value_start, after_value - value_start);
1676 /* Check VALUE to see if we are enabling, or disabling. */
1677 bool enable;
1678 if (value == "0" || value == "off")
1679 enable = false;
1680 else if (value == "1" || value == "on")
1681 enable = true;
1682 else
1683 return string_printf ("Invalid value '%s' for 'set debug %s'.\n",
1684 value.c_str (),
1685 std::string (mon, end - mon).c_str ());
1687 action_str = std::string (enable ? "+" : "-") + component;
1688 msg = string_printf ("Debug output for '%s' %s.\n", component.c_str (),
1689 enable ? "enabled" : "disabled");
1692 gdb_assert (!msg.empty ());
1693 gdb_assert (!action_str.empty ());
1697 parse_debug_options (action_str.c_str ());
1698 monitor_output (msg.c_str ());
1700 catch (const gdb_exception_error &exception)
1702 return string_printf ("Error: %s\n", exception.what ());
1705 return {};
1708 /* Handle monitor commands not handled by target-specific handlers. */
1710 static void
1711 handle_monitor_command (char *mon, char *own_buf)
1713 if (startswith (mon, "set debug "))
1715 std::string error_msg
1716 = handle_general_monitor_debug (mon + sizeof ("set debug ") - 1);
1718 if (!error_msg.empty ())
1720 monitor_output (error_msg.c_str ());
1721 monitor_show_help ();
1722 write_enn (own_buf);
1725 else if (strcmp (mon, "set debug-hw-points 1") == 0)
1727 show_debug_regs = 1;
1728 monitor_output ("H/W point debugging output enabled.\n");
1730 else if (strcmp (mon, "set debug-hw-points 0") == 0)
1732 show_debug_regs = 0;
1733 monitor_output ("H/W point debugging output disabled.\n");
1735 else if (startswith (mon, "set debug-format "))
1737 std::string error_msg
1738 = parse_debug_format_options (mon + sizeof ("set debug-format ") - 1,
1741 if (!error_msg.empty ())
1743 monitor_output (error_msg.c_str ());
1744 monitor_show_help ();
1745 write_enn (own_buf);
1748 else if (strcmp (mon, "set debug-file") == 0)
1749 debug_set_output (nullptr);
1750 else if (startswith (mon, "set debug-file "))
1751 debug_set_output (mon + sizeof ("set debug-file ") - 1);
1752 else if (strcmp (mon, "help") == 0)
1753 monitor_show_help ();
1754 else if (strcmp (mon, "exit") == 0)
1755 exit_requested = true;
1756 else
1758 monitor_output ("Unknown monitor command.\n\n");
1759 monitor_show_help ();
1760 write_enn (own_buf);
1764 /* Associates a callback with each supported qXfer'able object. */
1766 struct qxfer
1768 /* The object this handler handles. */
1769 const char *object;
1771 /* Request that the target transfer up to LEN 8-bit bytes of the
1772 target's OBJECT. The OFFSET, for a seekable object, specifies
1773 the starting point. The ANNEX can be used to provide additional
1774 data-specific information to the target.
1776 Return the number of bytes actually transfered, zero when no
1777 further transfer is possible, -1 on error, -2 when the transfer
1778 is not supported, and -3 on a verbose error message that should
1779 be preserved. Return of a positive value smaller than LEN does
1780 not indicate the end of the object, only the end of the transfer.
1782 One, and only one, of readbuf or writebuf must be non-NULL. */
1783 int (*xfer) (const char *annex,
1784 gdb_byte *readbuf, const gdb_byte *writebuf,
1785 ULONGEST offset, LONGEST len);
1788 /* Handle qXfer:auxv:read. */
1790 static int
1791 handle_qxfer_auxv (const char *annex,
1792 gdb_byte *readbuf, const gdb_byte *writebuf,
1793 ULONGEST offset, LONGEST len)
1795 if (!the_target->supports_read_auxv () || writebuf != NULL)
1796 return -2;
1798 if (annex[0] != '\0' || current_thread == NULL)
1799 return -1;
1801 return the_target->read_auxv (current_thread->id.pid (), offset, readbuf,
1802 len);
1805 /* Handle qXfer:exec-file:read. */
1807 static int
1808 handle_qxfer_exec_file (const char *annex,
1809 gdb_byte *readbuf, const gdb_byte *writebuf,
1810 ULONGEST offset, LONGEST len)
1812 ULONGEST pid;
1813 int total_len;
1815 if (!the_target->supports_pid_to_exec_file () || writebuf != NULL)
1816 return -2;
1818 if (annex[0] == '\0')
1820 if (current_thread == NULL)
1821 return -1;
1823 pid = pid_of (current_thread);
1825 else
1827 annex = unpack_varlen_hex (annex, &pid);
1828 if (annex[0] != '\0')
1829 return -1;
1832 if (pid <= 0)
1833 return -1;
1835 const char *file = the_target->pid_to_exec_file (pid);
1836 if (file == NULL)
1837 return -1;
1839 total_len = strlen (file);
1841 if (offset > total_len)
1842 return -1;
1844 if (offset + len > total_len)
1845 len = total_len - offset;
1847 memcpy (readbuf, file + offset, len);
1848 return len;
1851 /* Handle qXfer:features:read. */
1853 static int
1854 handle_qxfer_features (const char *annex,
1855 gdb_byte *readbuf, const gdb_byte *writebuf,
1856 ULONGEST offset, LONGEST len)
1858 const char *document;
1859 size_t total_len;
1861 if (writebuf != NULL)
1862 return -2;
1864 if (!target_running ())
1865 return -1;
1867 /* Grab the correct annex. */
1868 document = get_features_xml (annex);
1869 if (document == NULL)
1870 return -1;
1872 total_len = strlen (document);
1874 if (offset > total_len)
1875 return -1;
1877 if (offset + len > total_len)
1878 len = total_len - offset;
1880 memcpy (readbuf, document + offset, len);
1881 return len;
1884 /* Handle qXfer:libraries:read. */
1886 static int
1887 handle_qxfer_libraries (const char *annex,
1888 gdb_byte *readbuf, const gdb_byte *writebuf,
1889 ULONGEST offset, LONGEST len)
1891 if (writebuf != NULL)
1892 return -2;
1894 if (annex[0] != '\0' || current_thread == NULL)
1895 return -1;
1897 std::string document = "<library-list version=\"1.0\">\n";
1899 process_info *proc = current_process ();
1900 for (const dll_info &dll : proc->all_dlls)
1901 document += string_printf
1902 (" <library name=\"%s\"><segment address=\"0x%s\"/></library>\n",
1903 dll.name.c_str (), paddress (dll.base_addr));
1905 document += "</library-list>\n";
1907 if (offset > document.length ())
1908 return -1;
1910 if (offset + len > document.length ())
1911 len = document.length () - offset;
1913 memcpy (readbuf, &document[offset], len);
1915 return len;
1918 /* Handle qXfer:libraries-svr4:read. */
1920 static int
1921 handle_qxfer_libraries_svr4 (const char *annex,
1922 gdb_byte *readbuf, const gdb_byte *writebuf,
1923 ULONGEST offset, LONGEST len)
1925 if (writebuf != NULL)
1926 return -2;
1928 if (current_thread == NULL
1929 || !the_target->supports_qxfer_libraries_svr4 ())
1930 return -1;
1932 return the_target->qxfer_libraries_svr4 (annex, readbuf, writebuf,
1933 offset, len);
1936 /* Handle qXfer:osadata:read. */
1938 static int
1939 handle_qxfer_osdata (const char *annex,
1940 gdb_byte *readbuf, const gdb_byte *writebuf,
1941 ULONGEST offset, LONGEST len)
1943 if (!the_target->supports_qxfer_osdata () || writebuf != NULL)
1944 return -2;
1946 return the_target->qxfer_osdata (annex, readbuf, NULL, offset, len);
1949 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1951 static int
1952 handle_qxfer_siginfo (const char *annex,
1953 gdb_byte *readbuf, const gdb_byte *writebuf,
1954 ULONGEST offset, LONGEST len)
1956 if (!the_target->supports_qxfer_siginfo ())
1957 return -2;
1959 if (annex[0] != '\0' || current_thread == NULL)
1960 return -1;
1962 return the_target->qxfer_siginfo (annex, readbuf, writebuf, offset, len);
1965 /* Handle qXfer:statictrace:read. */
1967 static int
1968 handle_qxfer_statictrace (const char *annex,
1969 gdb_byte *readbuf, const gdb_byte *writebuf,
1970 ULONGEST offset, LONGEST len)
1972 client_state &cs = get_client_state ();
1973 ULONGEST nbytes;
1975 if (writebuf != NULL)
1976 return -2;
1978 if (annex[0] != '\0' || current_thread == NULL
1979 || cs.current_traceframe == -1)
1980 return -1;
1982 if (traceframe_read_sdata (cs.current_traceframe, offset,
1983 readbuf, len, &nbytes))
1984 return -1;
1985 return nbytes;
1988 /* Helper for handle_qxfer_threads_proper.
1989 Emit the XML to describe the thread of INF. */
1991 static void
1992 handle_qxfer_threads_worker (thread_info *thread, std::string *buffer)
1994 ptid_t ptid = ptid_of (thread);
1995 char ptid_s[100];
1996 int core = target_core_of_thread (ptid);
1997 char core_s[21];
1998 const char *name = target_thread_name (ptid);
1999 int handle_len;
2000 gdb_byte *handle;
2001 bool handle_status = target_thread_handle (ptid, &handle, &handle_len);
2003 /* If this is a (v)fork/clone child (has a (v)fork/clone parent),
2004 GDB does not yet know about this thread, and must not know about
2005 it until it gets the corresponding (v)fork/clone event. Exclude
2006 this thread from the list. */
2007 if (target_thread_pending_parent (thread) != nullptr)
2008 return;
2010 write_ptid (ptid_s, ptid);
2012 string_xml_appendf (*buffer, "<thread id=\"%s\"", ptid_s);
2014 if (core != -1)
2016 sprintf (core_s, "%d", core);
2017 string_xml_appendf (*buffer, " core=\"%s\"", core_s);
2020 if (name != NULL)
2021 string_xml_appendf (*buffer, " name=\"%s\"", name);
2023 if (handle_status)
2025 char *handle_s = (char *) alloca (handle_len * 2 + 1);
2026 bin2hex (handle, handle_s, handle_len);
2027 string_xml_appendf (*buffer, " handle=\"%s\"", handle_s);
2030 string_xml_appendf (*buffer, "/>\n");
2033 /* Helper for handle_qxfer_threads. Return true on success, false
2034 otherwise. */
2036 static bool
2037 handle_qxfer_threads_proper (std::string *buffer)
2039 *buffer += "<threads>\n";
2041 /* The target may need to access memory and registers (e.g. via
2042 libthread_db) to fetch thread properties. Even if don't need to
2043 stop threads to access memory, we still will need to be able to
2044 access registers, and other ptrace accesses like
2045 PTRACE_GET_THREAD_AREA that require a paused thread. Pause all
2046 threads here, so that we pause each thread at most once for all
2047 accesses. */
2048 if (non_stop)
2049 target_pause_all (true);
2051 for_each_thread ([&] (thread_info *thread)
2053 handle_qxfer_threads_worker (thread, buffer);
2056 if (non_stop)
2057 target_unpause_all (true);
2059 *buffer += "</threads>\n";
2060 return true;
2063 /* Handle qXfer:threads:read. */
2065 static int
2066 handle_qxfer_threads (const char *annex,
2067 gdb_byte *readbuf, const gdb_byte *writebuf,
2068 ULONGEST offset, LONGEST len)
2070 static std::string result;
2072 if (writebuf != NULL)
2073 return -2;
2075 if (annex[0] != '\0')
2076 return -1;
2078 if (offset == 0)
2080 /* When asked for data at offset 0, generate everything and store into
2081 'result'. Successive reads will be served off 'result'. */
2082 result.clear ();
2084 bool res = handle_qxfer_threads_proper (&result);
2086 if (!res)
2087 return -1;
2090 if (offset >= result.length ())
2092 /* We're out of data. */
2093 result.clear ();
2094 return 0;
2097 if (len > result.length () - offset)
2098 len = result.length () - offset;
2100 memcpy (readbuf, result.c_str () + offset, len);
2102 return len;
2105 /* Handle qXfer:traceframe-info:read. */
2107 static int
2108 handle_qxfer_traceframe_info (const char *annex,
2109 gdb_byte *readbuf, const gdb_byte *writebuf,
2110 ULONGEST offset, LONGEST len)
2112 client_state &cs = get_client_state ();
2113 static std::string result;
2115 if (writebuf != NULL)
2116 return -2;
2118 if (!target_running () || annex[0] != '\0' || cs.current_traceframe == -1)
2119 return -1;
2121 if (offset == 0)
2123 /* When asked for data at offset 0, generate everything and
2124 store into 'result'. Successive reads will be served off
2125 'result'. */
2126 result.clear ();
2128 traceframe_read_info (cs.current_traceframe, &result);
2131 if (offset >= result.length ())
2133 /* We're out of data. */
2134 result.clear ();
2135 return 0;
2138 if (len > result.length () - offset)
2139 len = result.length () - offset;
2141 memcpy (readbuf, result.c_str () + offset, len);
2142 return len;
2145 /* Handle qXfer:fdpic:read. */
2147 static int
2148 handle_qxfer_fdpic (const char *annex, gdb_byte *readbuf,
2149 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
2151 if (!the_target->supports_read_loadmap ())
2152 return -2;
2154 if (current_thread == NULL)
2155 return -1;
2157 return the_target->read_loadmap (annex, offset, readbuf, len);
2160 /* Handle qXfer:btrace:read. */
2162 static int
2163 handle_qxfer_btrace (const char *annex,
2164 gdb_byte *readbuf, const gdb_byte *writebuf,
2165 ULONGEST offset, LONGEST len)
2167 client_state &cs = get_client_state ();
2168 static std::string cache;
2169 struct thread_info *thread;
2170 enum btrace_read_type type;
2171 int result;
2173 if (writebuf != NULL)
2174 return -2;
2176 if (cs.general_thread == null_ptid
2177 || cs.general_thread == minus_one_ptid)
2179 strcpy (cs.own_buf, "E.Must select a single thread.");
2180 return -3;
2183 thread = find_thread_ptid (cs.general_thread);
2184 if (thread == NULL)
2186 strcpy (cs.own_buf, "E.No such thread.");
2187 return -3;
2190 if (thread->btrace == NULL)
2192 strcpy (cs.own_buf, "E.Btrace not enabled.");
2193 return -3;
2196 if (strcmp (annex, "all") == 0)
2197 type = BTRACE_READ_ALL;
2198 else if (strcmp (annex, "new") == 0)
2199 type = BTRACE_READ_NEW;
2200 else if (strcmp (annex, "delta") == 0)
2201 type = BTRACE_READ_DELTA;
2202 else
2204 strcpy (cs.own_buf, "E.Bad annex.");
2205 return -3;
2208 if (offset == 0)
2210 cache.clear ();
2214 result = target_read_btrace (thread->btrace, &cache, type);
2215 if (result != 0)
2216 memcpy (cs.own_buf, cache.c_str (), cache.length ());
2218 catch (const gdb_exception_error &exception)
2220 sprintf (cs.own_buf, "E.%s", exception.what ());
2221 result = -1;
2224 if (result != 0)
2225 return -3;
2227 else if (offset > cache.length ())
2229 cache.clear ();
2230 return -3;
2233 if (len > cache.length () - offset)
2234 len = cache.length () - offset;
2236 memcpy (readbuf, cache.c_str () + offset, len);
2238 return len;
2241 /* Handle qXfer:btrace-conf:read. */
2243 static int
2244 handle_qxfer_btrace_conf (const char *annex,
2245 gdb_byte *readbuf, const gdb_byte *writebuf,
2246 ULONGEST offset, LONGEST len)
2248 client_state &cs = get_client_state ();
2249 static std::string cache;
2250 struct thread_info *thread;
2251 int result;
2253 if (writebuf != NULL)
2254 return -2;
2256 if (annex[0] != '\0')
2257 return -1;
2259 if (cs.general_thread == null_ptid
2260 || cs.general_thread == minus_one_ptid)
2262 strcpy (cs.own_buf, "E.Must select a single thread.");
2263 return -3;
2266 thread = find_thread_ptid (cs.general_thread);
2267 if (thread == NULL)
2269 strcpy (cs.own_buf, "E.No such thread.");
2270 return -3;
2273 if (thread->btrace == NULL)
2275 strcpy (cs.own_buf, "E.Btrace not enabled.");
2276 return -3;
2279 if (offset == 0)
2281 cache.clear ();
2285 result = target_read_btrace_conf (thread->btrace, &cache);
2286 if (result != 0)
2287 memcpy (cs.own_buf, cache.c_str (), cache.length ());
2289 catch (const gdb_exception_error &exception)
2291 sprintf (cs.own_buf, "E.%s", exception.what ());
2292 result = -1;
2295 if (result != 0)
2296 return -3;
2298 else if (offset > cache.length ())
2300 cache.clear ();
2301 return -3;
2304 if (len > cache.length () - offset)
2305 len = cache.length () - offset;
2307 memcpy (readbuf, cache.c_str () + offset, len);
2309 return len;
2312 static const struct qxfer qxfer_packets[] =
2314 { "auxv", handle_qxfer_auxv },
2315 { "btrace", handle_qxfer_btrace },
2316 { "btrace-conf", handle_qxfer_btrace_conf },
2317 { "exec-file", handle_qxfer_exec_file},
2318 { "fdpic", handle_qxfer_fdpic},
2319 { "features", handle_qxfer_features },
2320 { "libraries", handle_qxfer_libraries },
2321 { "libraries-svr4", handle_qxfer_libraries_svr4 },
2322 { "osdata", handle_qxfer_osdata },
2323 { "siginfo", handle_qxfer_siginfo },
2324 { "statictrace", handle_qxfer_statictrace },
2325 { "threads", handle_qxfer_threads },
2326 { "traceframe-info", handle_qxfer_traceframe_info },
2329 static int
2330 handle_qxfer (char *own_buf, int packet_len, int *new_packet_len_p)
2332 int i;
2333 char *object;
2334 char *rw;
2335 char *annex;
2336 char *offset;
2338 if (!startswith (own_buf, "qXfer:"))
2339 return 0;
2341 /* Grab the object, r/w and annex. */
2342 if (decode_xfer (own_buf + 6, &object, &rw, &annex, &offset) < 0)
2344 write_enn (own_buf);
2345 return 1;
2348 for (i = 0;
2349 i < sizeof (qxfer_packets) / sizeof (qxfer_packets[0]);
2350 i++)
2352 const struct qxfer *q = &qxfer_packets[i];
2354 if (strcmp (object, q->object) == 0)
2356 if (strcmp (rw, "read") == 0)
2358 unsigned char *data;
2359 int n;
2360 CORE_ADDR ofs;
2361 unsigned int len;
2363 /* Grab the offset and length. */
2364 if (decode_xfer_read (offset, &ofs, &len) < 0)
2366 write_enn (own_buf);
2367 return 1;
2370 /* Read one extra byte, as an indicator of whether there is
2371 more. */
2372 if (len > PBUFSIZ - 2)
2373 len = PBUFSIZ - 2;
2374 data = (unsigned char *) malloc (len + 1);
2375 if (data == NULL)
2377 write_enn (own_buf);
2378 return 1;
2380 n = (*q->xfer) (annex, data, NULL, ofs, len + 1);
2381 if (n == -2)
2383 free (data);
2384 return 0;
2386 else if (n == -3)
2388 /* Preserve error message. */
2390 else if (n < 0)
2391 write_enn (own_buf);
2392 else if (n > len)
2393 *new_packet_len_p = write_qxfer_response (own_buf, data, len, 1);
2394 else
2395 *new_packet_len_p = write_qxfer_response (own_buf, data, n, 0);
2397 free (data);
2398 return 1;
2400 else if (strcmp (rw, "write") == 0)
2402 int n;
2403 unsigned int len;
2404 CORE_ADDR ofs;
2405 unsigned char *data;
2407 strcpy (own_buf, "E00");
2408 data = (unsigned char *) malloc (packet_len - (offset - own_buf));
2409 if (data == NULL)
2411 write_enn (own_buf);
2412 return 1;
2414 if (decode_xfer_write (offset, packet_len - (offset - own_buf),
2415 &ofs, &len, data) < 0)
2417 free (data);
2418 write_enn (own_buf);
2419 return 1;
2422 n = (*q->xfer) (annex, NULL, data, ofs, len);
2423 if (n == -2)
2425 free (data);
2426 return 0;
2428 else if (n == -3)
2430 /* Preserve error message. */
2432 else if (n < 0)
2433 write_enn (own_buf);
2434 else
2435 sprintf (own_buf, "%x", n);
2437 free (data);
2438 return 1;
2441 return 0;
2445 return 0;
2448 /* Compute 32 bit CRC from inferior memory.
2450 On success, return 32 bit CRC.
2451 On failure, return (unsigned long long) -1. */
2453 static unsigned long long
2454 crc32 (CORE_ADDR base, int len, unsigned int crc)
2456 while (len--)
2458 unsigned char byte = 0;
2460 /* Return failure if memory read fails. */
2461 if (read_inferior_memory (base, &byte, 1) != 0)
2462 return (unsigned long long) -1;
2464 crc = xcrc32 (&byte, 1, crc);
2465 base++;
2467 return (unsigned long long) crc;
2470 /* Parse the qMemTags packet request into ADDR and LEN. */
2472 static void
2473 parse_fetch_memtags_request (char *request, CORE_ADDR *addr, size_t *len,
2474 int *type)
2476 gdb_assert (startswith (request, "qMemTags:"));
2478 const char *p = request + strlen ("qMemTags:");
2480 /* Read address and length. */
2481 unsigned int length = 0;
2482 p = decode_m_packet_params (p, addr, &length, ':');
2483 *len = length;
2485 /* Read the tag type. */
2486 ULONGEST tag_type = 0;
2487 p = unpack_varlen_hex (p, &tag_type);
2488 *type = (int) tag_type;
2491 /* Add supported btrace packets to BUF. */
2493 static void
2494 supported_btrace_packets (char *buf)
2496 strcat (buf, ";Qbtrace:bts+");
2497 strcat (buf, ";Qbtrace-conf:bts:size+");
2498 strcat (buf, ";Qbtrace:pt+");
2499 strcat (buf, ";Qbtrace-conf:pt:size+");
2500 strcat (buf, ";Qbtrace-conf:pt:ptwrite+");
2501 strcat (buf, ";Qbtrace:off+");
2502 strcat (buf, ";qXfer:btrace:read+");
2503 strcat (buf, ";qXfer:btrace-conf:read+");
2506 /* Handle all of the extended 'q' packets. */
2508 static void
2509 handle_query (char *own_buf, int packet_len, int *new_packet_len_p)
2511 client_state &cs = get_client_state ();
2512 static std::list<thread_info *>::const_iterator thread_iter;
2514 /* Reply the current thread id. */
2515 if (strcmp ("qC", own_buf) == 0 && !disable_packet_qC)
2517 ptid_t ptid;
2518 require_running_or_return (own_buf);
2520 if (cs.general_thread != null_ptid && cs.general_thread != minus_one_ptid)
2521 ptid = cs.general_thread;
2522 else
2524 thread_iter = all_threads.begin ();
2525 ptid = (*thread_iter)->id;
2528 sprintf (own_buf, "QC");
2529 own_buf += 2;
2530 write_ptid (own_buf, ptid);
2531 return;
2534 if (strcmp ("qSymbol::", own_buf) == 0)
2536 scoped_restore_current_thread restore_thread;
2538 /* For qSymbol, GDB only changes the current thread if the
2539 previous current thread was of a different process. So if
2540 the previous thread is gone, we need to pick another one of
2541 the same process. This can happen e.g., if we followed an
2542 exec in a non-leader thread. */
2543 if (current_thread == NULL)
2545 thread_info *any_thread
2546 = find_any_thread_of_pid (cs.general_thread.pid ());
2547 switch_to_thread (any_thread);
2549 /* Just in case, if we didn't find a thread, then bail out
2550 instead of crashing. */
2551 if (current_thread == NULL)
2553 write_enn (own_buf);
2554 return;
2558 /* GDB is suggesting new symbols have been loaded. This may
2559 mean a new shared library has been detected as loaded, so
2560 take the opportunity to check if breakpoints we think are
2561 inserted, still are. Note that it isn't guaranteed that
2562 we'll see this when a shared library is loaded, and nor will
2563 we see this for unloads (although breakpoints in unloaded
2564 libraries shouldn't trigger), as GDB may not find symbols for
2565 the library at all. We also re-validate breakpoints when we
2566 see a second GDB breakpoint for the same address, and or when
2567 we access breakpoint shadows. */
2568 validate_breakpoints ();
2570 if (target_supports_tracepoints ())
2571 tracepoint_look_up_symbols ();
2573 if (current_thread != NULL)
2574 the_target->look_up_symbols ();
2576 strcpy (own_buf, "OK");
2577 return;
2580 if (!disable_packet_qfThreadInfo)
2582 if (strcmp ("qfThreadInfo", own_buf) == 0)
2584 require_running_or_return (own_buf);
2585 thread_iter = all_threads.begin ();
2587 *own_buf++ = 'm';
2588 ptid_t ptid = (*thread_iter)->id;
2589 write_ptid (own_buf, ptid);
2590 thread_iter++;
2591 return;
2594 if (strcmp ("qsThreadInfo", own_buf) == 0)
2596 require_running_or_return (own_buf);
2597 if (thread_iter != all_threads.end ())
2599 *own_buf++ = 'm';
2600 ptid_t ptid = (*thread_iter)->id;
2601 write_ptid (own_buf, ptid);
2602 thread_iter++;
2603 return;
2605 else
2607 sprintf (own_buf, "l");
2608 return;
2613 if (the_target->supports_read_offsets ()
2614 && strcmp ("qOffsets", own_buf) == 0)
2616 CORE_ADDR text, data;
2618 require_running_or_return (own_buf);
2619 if (the_target->read_offsets (&text, &data))
2620 sprintf (own_buf, "Text=%lX;Data=%lX;Bss=%lX",
2621 (long)text, (long)data, (long)data);
2622 else
2623 write_enn (own_buf);
2625 return;
2628 /* Protocol features query. */
2629 if (startswith (own_buf, "qSupported")
2630 && (own_buf[10] == ':' || own_buf[10] == '\0'))
2632 char *p = &own_buf[10];
2633 int gdb_supports_qRelocInsn = 0;
2635 /* Process each feature being provided by GDB. The first
2636 feature will follow a ':', and latter features will follow
2637 ';'. */
2638 if (*p == ':')
2640 std::vector<std::string> qsupported;
2641 std::vector<const char *> unknowns;
2643 /* Two passes, to avoid nested strtok calls in
2644 target_process_qsupported. */
2645 char *saveptr;
2646 for (p = strtok_r (p + 1, ";", &saveptr);
2647 p != NULL;
2648 p = strtok_r (NULL, ";", &saveptr))
2649 qsupported.emplace_back (p);
2651 for (const std::string &feature : qsupported)
2653 if (feature == "multiprocess+")
2655 /* GDB supports and wants multi-process support if
2656 possible. */
2657 if (target_supports_multi_process ())
2658 cs.multi_process = 1;
2660 else if (feature == "qRelocInsn+")
2662 /* GDB supports relocate instruction requests. */
2663 gdb_supports_qRelocInsn = 1;
2665 else if (feature == "swbreak+")
2667 /* GDB wants us to report whether a trap is caused
2668 by a software breakpoint and for us to handle PC
2669 adjustment if necessary on this target. */
2670 if (target_supports_stopped_by_sw_breakpoint ())
2671 cs.swbreak_feature = 1;
2673 else if (feature == "hwbreak+")
2675 /* GDB wants us to report whether a trap is caused
2676 by a hardware breakpoint. */
2677 if (target_supports_stopped_by_hw_breakpoint ())
2678 cs.hwbreak_feature = 1;
2680 else if (feature == "fork-events+")
2682 /* GDB supports and wants fork events if possible. */
2683 if (target_supports_fork_events ())
2684 cs.report_fork_events = 1;
2686 else if (feature == "vfork-events+")
2688 /* GDB supports and wants vfork events if possible. */
2689 if (target_supports_vfork_events ())
2690 cs.report_vfork_events = 1;
2692 else if (feature == "exec-events+")
2694 /* GDB supports and wants exec events if possible. */
2695 if (target_supports_exec_events ())
2696 cs.report_exec_events = 1;
2698 else if (feature == "vContSupported+")
2699 cs.vCont_supported = 1;
2700 else if (feature == "QThreadEvents+")
2702 else if (feature == "QThreadOptions+")
2704 else if (feature == "no-resumed+")
2706 /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
2707 events. */
2708 report_no_resumed = true;
2710 else if (feature == "memory-tagging+")
2712 /* GDB supports memory tagging features. */
2713 if (target_supports_memory_tagging ())
2714 cs.memory_tagging_feature = true;
2716 else if (feature == "error-message+")
2717 cs.error_message_supported = true;
2718 else
2720 /* Move the unknown features all together. */
2721 unknowns.push_back (feature.c_str ());
2725 /* Give the target backend a chance to process the unknown
2726 features. */
2727 target_process_qsupported (unknowns);
2730 sprintf (own_buf,
2731 "PacketSize=%x;QPassSignals+;QProgramSignals+;"
2732 "QStartupWithShell+;QEnvironmentHexEncoded+;"
2733 "QEnvironmentReset+;QEnvironmentUnset+;"
2734 "QSetWorkingDir+",
2735 PBUFSIZ - 1);
2737 if (target_supports_catch_syscall ())
2738 strcat (own_buf, ";QCatchSyscalls+");
2740 if (the_target->supports_qxfer_libraries_svr4 ())
2741 strcat (own_buf, ";qXfer:libraries-svr4:read+"
2742 ";augmented-libraries-svr4-read+");
2743 else
2745 /* We do not have any hook to indicate whether the non-SVR4 target
2746 backend supports qXfer:libraries:read, so always report it. */
2747 strcat (own_buf, ";qXfer:libraries:read+");
2750 if (the_target->supports_read_auxv ())
2751 strcat (own_buf, ";qXfer:auxv:read+");
2753 if (the_target->supports_qxfer_siginfo ())
2754 strcat (own_buf, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2756 if (the_target->supports_read_loadmap ())
2757 strcat (own_buf, ";qXfer:fdpic:read+");
2759 /* We always report qXfer:features:read, as targets may
2760 install XML files on a subsequent call to arch_setup.
2761 If we reported to GDB on startup that we don't support
2762 qXfer:feature:read at all, we will never be re-queried. */
2763 strcat (own_buf, ";qXfer:features:read+");
2765 if (cs.transport_is_reliable)
2766 strcat (own_buf, ";QStartNoAckMode+");
2768 if (the_target->supports_qxfer_osdata ())
2769 strcat (own_buf, ";qXfer:osdata:read+");
2771 if (target_supports_multi_process ())
2772 strcat (own_buf, ";multiprocess+");
2774 if (target_supports_fork_events ())
2775 strcat (own_buf, ";fork-events+");
2777 if (target_supports_vfork_events ())
2778 strcat (own_buf, ";vfork-events+");
2780 if (target_supports_exec_events ())
2781 strcat (own_buf, ";exec-events+");
2783 if (target_supports_non_stop ())
2784 strcat (own_buf, ";QNonStop+");
2786 if (target_supports_disable_randomization ())
2787 strcat (own_buf, ";QDisableRandomization+");
2789 strcat (own_buf, ";qXfer:threads:read+");
2791 if (target_supports_tracepoints ())
2793 strcat (own_buf, ";ConditionalTracepoints+");
2794 strcat (own_buf, ";TraceStateVariables+");
2795 strcat (own_buf, ";TracepointSource+");
2796 strcat (own_buf, ";DisconnectedTracing+");
2797 if (gdb_supports_qRelocInsn && target_supports_fast_tracepoints ())
2798 strcat (own_buf, ";FastTracepoints+");
2799 strcat (own_buf, ";StaticTracepoints+");
2800 strcat (own_buf, ";InstallInTrace+");
2801 strcat (own_buf, ";qXfer:statictrace:read+");
2802 strcat (own_buf, ";qXfer:traceframe-info:read+");
2803 strcat (own_buf, ";EnableDisableTracepoints+");
2804 strcat (own_buf, ";QTBuffer:size+");
2805 strcat (own_buf, ";tracenz+");
2808 if (target_supports_hardware_single_step ()
2809 || target_supports_software_single_step () )
2811 strcat (own_buf, ";ConditionalBreakpoints+");
2813 strcat (own_buf, ";BreakpointCommands+");
2815 if (target_supports_agent ())
2816 strcat (own_buf, ";QAgent+");
2818 if (the_target->supports_btrace ())
2819 supported_btrace_packets (own_buf);
2821 if (target_supports_stopped_by_sw_breakpoint ())
2822 strcat (own_buf, ";swbreak+");
2824 if (target_supports_stopped_by_hw_breakpoint ())
2825 strcat (own_buf, ";hwbreak+");
2827 if (the_target->supports_pid_to_exec_file ())
2828 strcat (own_buf, ";qXfer:exec-file:read+");
2830 strcat (own_buf, ";vContSupported+");
2832 gdb_thread_options supported_options = target_supported_thread_options ();
2833 if (supported_options != 0)
2835 char *end_buf = own_buf + strlen (own_buf);
2836 sprintf (end_buf, ";QThreadOptions=%s",
2837 phex_nz (supported_options, sizeof (supported_options)));
2840 strcat (own_buf, ";QThreadEvents+");
2842 strcat (own_buf, ";no-resumed+");
2844 if (target_supports_memory_tagging ())
2845 strcat (own_buf, ";memory-tagging+");
2847 /* Reinitialize components as needed for the new connection. */
2848 hostio_handle_new_gdb_connection ();
2849 target_handle_new_gdb_connection ();
2851 return;
2854 /* Thread-local storage support. */
2855 if (the_target->supports_get_tls_address ()
2856 && startswith (own_buf, "qGetTLSAddr:"))
2858 char *p = own_buf + 12;
2859 CORE_ADDR parts[2], address = 0;
2860 int i, err;
2861 ptid_t ptid = null_ptid;
2863 require_running_or_return (own_buf);
2865 for (i = 0; i < 3; i++)
2867 char *p2;
2868 int len;
2870 if (p == NULL)
2871 break;
2873 p2 = strchr (p, ',');
2874 if (p2)
2876 len = p2 - p;
2877 p2++;
2879 else
2881 len = strlen (p);
2882 p2 = NULL;
2885 if (i == 0)
2886 ptid = read_ptid (p, NULL);
2887 else
2888 decode_address (&parts[i - 1], p, len);
2889 p = p2;
2892 if (p != NULL || i < 3)
2893 err = 1;
2894 else
2896 struct thread_info *thread = find_thread_ptid (ptid);
2898 if (thread == NULL)
2899 err = 2;
2900 else
2901 err = the_target->get_tls_address (thread, parts[0], parts[1],
2902 &address);
2905 if (err == 0)
2907 strcpy (own_buf, paddress(address));
2908 return;
2910 else if (err > 0)
2912 write_enn (own_buf);
2913 return;
2916 /* Otherwise, pretend we do not understand this packet. */
2919 /* Windows OS Thread Information Block address support. */
2920 if (the_target->supports_get_tib_address ()
2921 && startswith (own_buf, "qGetTIBAddr:"))
2923 const char *annex;
2924 int n;
2925 CORE_ADDR tlb;
2926 ptid_t ptid = read_ptid (own_buf + 12, &annex);
2928 n = the_target->get_tib_address (ptid, &tlb);
2929 if (n == 1)
2931 strcpy (own_buf, paddress(tlb));
2932 return;
2934 else if (n == 0)
2936 write_enn (own_buf);
2937 return;
2939 return;
2942 /* Handle "monitor" commands. */
2943 if (startswith (own_buf, "qRcmd,"))
2945 char *mon = (char *) malloc (PBUFSIZ);
2946 int len = strlen (own_buf + 6);
2948 if (mon == NULL)
2950 write_enn (own_buf);
2951 return;
2954 if ((len % 2) != 0
2955 || hex2bin (own_buf + 6, (gdb_byte *) mon, len / 2) != len / 2)
2957 write_enn (own_buf);
2958 free (mon);
2959 return;
2961 mon[len / 2] = '\0';
2963 write_ok (own_buf);
2965 if (the_target->handle_monitor_command (mon) == 0)
2966 /* Default processing. */
2967 handle_monitor_command (mon, own_buf);
2969 free (mon);
2970 return;
2973 if (startswith (own_buf, "qSearch:memory:"))
2975 require_running_or_return (own_buf);
2976 handle_search_memory (own_buf, packet_len);
2977 return;
2980 if (strcmp (own_buf, "qAttached") == 0
2981 || startswith (own_buf, "qAttached:"))
2983 struct process_info *process;
2985 if (own_buf[sizeof ("qAttached") - 1])
2987 int pid = strtoul (own_buf + sizeof ("qAttached:") - 1, NULL, 16);
2988 process = find_process_pid (pid);
2990 else
2992 require_running_or_return (own_buf);
2993 process = current_process ();
2996 if (process == NULL)
2998 write_enn (own_buf);
2999 return;
3002 strcpy (own_buf, process->attached ? "1" : "0");
3003 return;
3006 if (startswith (own_buf, "qCRC:"))
3008 /* CRC check (compare-section). */
3009 const char *comma;
3010 ULONGEST base;
3011 int len;
3012 unsigned long long crc;
3014 require_running_or_return (own_buf);
3015 comma = unpack_varlen_hex (own_buf + 5, &base);
3016 if (*comma++ != ',')
3018 write_enn (own_buf);
3019 return;
3021 len = strtoul (comma, NULL, 16);
3022 crc = crc32 (base, len, 0xffffffff);
3023 /* Check for memory failure. */
3024 if (crc == (unsigned long long) -1)
3026 write_enn (own_buf);
3027 return;
3029 sprintf (own_buf, "C%lx", (unsigned long) crc);
3030 return;
3033 if (handle_qxfer (own_buf, packet_len, new_packet_len_p))
3034 return;
3036 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf))
3037 return;
3039 /* Handle fetch memory tags packets. */
3040 if (startswith (own_buf, "qMemTags:")
3041 && target_supports_memory_tagging ())
3043 gdb::byte_vector tags;
3044 CORE_ADDR addr = 0;
3045 size_t len = 0;
3046 int type = 0;
3048 require_running_or_return (own_buf);
3050 parse_fetch_memtags_request (own_buf, &addr, &len, &type);
3052 bool ret = the_target->fetch_memtags (addr, len, tags, type);
3054 if (ret)
3055 ret = create_fetch_memtags_reply (own_buf, tags);
3057 if (!ret)
3058 write_enn (own_buf);
3060 *new_packet_len_p = strlen (own_buf);
3061 return;
3064 /* Otherwise we didn't know what packet it was. Say we didn't
3065 understand it. */
3066 own_buf[0] = 0;
3069 static void gdb_wants_all_threads_stopped (void);
3070 static void resume (struct thread_resume *actions, size_t n);
3072 /* The callback that is passed to visit_actioned_threads. */
3073 typedef int (visit_actioned_threads_callback_ftype)
3074 (const struct thread_resume *, struct thread_info *);
3076 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
3077 true if CALLBACK returns true. Returns false if no matching thread
3078 is found or CALLBACK results false.
3079 Note: This function is itself a callback for find_thread. */
3081 static bool
3082 visit_actioned_threads (thread_info *thread,
3083 const struct thread_resume *actions,
3084 size_t num_actions,
3085 visit_actioned_threads_callback_ftype *callback)
3087 for (size_t i = 0; i < num_actions; i++)
3089 const struct thread_resume *action = &actions[i];
3091 if (action->thread == minus_one_ptid
3092 || action->thread == thread->id
3093 || ((action->thread.pid ()
3094 == thread->id.pid ())
3095 && action->thread.lwp () == -1))
3097 if ((*callback) (action, thread))
3098 return true;
3102 return false;
3105 /* Callback for visit_actioned_threads. If the thread has a pending
3106 status to report, report it now. */
3108 static int
3109 handle_pending_status (const struct thread_resume *resumption,
3110 struct thread_info *thread)
3112 client_state &cs = get_client_state ();
3113 if (thread->status_pending_p)
3115 thread->status_pending_p = 0;
3117 cs.last_status = thread->last_status;
3118 cs.last_ptid = thread->id;
3119 prepare_resume_reply (cs.own_buf, cs.last_ptid, cs.last_status);
3120 return 1;
3122 return 0;
3125 /* Parse vCont packets. */
3126 static void
3127 handle_v_cont (char *own_buf)
3129 const char *p;
3130 int n = 0, i = 0;
3131 struct thread_resume *resume_info;
3132 struct thread_resume default_action { null_ptid };
3134 /* Count the number of semicolons in the packet. There should be one
3135 for every action. */
3136 p = &own_buf[5];
3137 while (p)
3139 n++;
3140 p++;
3141 p = strchr (p, ';');
3144 resume_info = (struct thread_resume *) malloc (n * sizeof (resume_info[0]));
3145 if (resume_info == NULL)
3146 goto err;
3148 p = &own_buf[5];
3149 while (*p)
3151 p++;
3153 memset (&resume_info[i], 0, sizeof resume_info[i]);
3155 if (p[0] == 's' || p[0] == 'S')
3156 resume_info[i].kind = resume_step;
3157 else if (p[0] == 'r')
3158 resume_info[i].kind = resume_step;
3159 else if (p[0] == 'c' || p[0] == 'C')
3160 resume_info[i].kind = resume_continue;
3161 else if (p[0] == 't')
3162 resume_info[i].kind = resume_stop;
3163 else
3164 goto err;
3166 if (p[0] == 'S' || p[0] == 'C')
3168 char *q;
3169 int sig = strtol (p + 1, &q, 16);
3170 if (p == q)
3171 goto err;
3172 p = q;
3174 if (!gdb_signal_to_host_p ((enum gdb_signal) sig))
3175 goto err;
3176 resume_info[i].sig = gdb_signal_to_host ((enum gdb_signal) sig);
3178 else if (p[0] == 'r')
3180 ULONGEST addr;
3182 p = unpack_varlen_hex (p + 1, &addr);
3183 resume_info[i].step_range_start = addr;
3185 if (*p != ',')
3186 goto err;
3188 p = unpack_varlen_hex (p + 1, &addr);
3189 resume_info[i].step_range_end = addr;
3191 else
3193 p = p + 1;
3196 if (p[0] == 0)
3198 resume_info[i].thread = minus_one_ptid;
3199 default_action = resume_info[i];
3201 /* Note: we don't increment i here, we'll overwrite this entry
3202 the next time through. */
3204 else if (p[0] == ':')
3206 const char *q;
3207 ptid_t ptid = read_ptid (p + 1, &q);
3209 if (p == q)
3210 goto err;
3211 p = q;
3212 if (p[0] != ';' && p[0] != 0)
3213 goto err;
3215 resume_info[i].thread = ptid;
3217 i++;
3221 if (i < n)
3222 resume_info[i] = default_action;
3224 resume (resume_info, n);
3225 free (resume_info);
3226 return;
3228 err:
3229 write_enn (own_buf);
3230 free (resume_info);
3231 return;
3234 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
3236 static void
3237 resume (struct thread_resume *actions, size_t num_actions)
3239 client_state &cs = get_client_state ();
3240 if (!non_stop)
3242 /* Check if among the threads that GDB wants actioned, there's
3243 one with a pending status to report. If so, skip actually
3244 resuming/stopping and report the pending event
3245 immediately. */
3247 thread_info *thread_with_status = find_thread ([&] (thread_info *thread)
3249 return visit_actioned_threads (thread, actions, num_actions,
3250 handle_pending_status);
3253 if (thread_with_status != NULL)
3254 return;
3256 enable_async_io ();
3259 the_target->resume (actions, num_actions);
3261 if (non_stop)
3262 write_ok (cs.own_buf);
3263 else
3265 cs.last_ptid = mywait (minus_one_ptid, &cs.last_status, 0, 1);
3267 if (cs.last_status.kind () == TARGET_WAITKIND_NO_RESUMED
3268 && !report_no_resumed)
3270 /* The client does not support this stop reply. At least
3271 return error. */
3272 sprintf (cs.own_buf, "E.No unwaited-for children left.");
3273 disable_async_io ();
3274 return;
3277 if (cs.last_status.kind () != TARGET_WAITKIND_EXITED
3278 && cs.last_status.kind () != TARGET_WAITKIND_SIGNALLED
3279 && cs.last_status.kind () != TARGET_WAITKIND_THREAD_EXITED
3280 && cs.last_status.kind () != TARGET_WAITKIND_NO_RESUMED)
3281 current_thread->last_status = cs.last_status;
3283 /* From the client's perspective, all-stop mode always stops all
3284 threads implicitly (and the target backend has already done
3285 so by now). Tag all threads as "want-stopped", so we don't
3286 resume them implicitly without the client telling us to. */
3287 gdb_wants_all_threads_stopped ();
3288 prepare_resume_reply (cs.own_buf, cs.last_ptid, cs.last_status);
3289 disable_async_io ();
3291 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
3292 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
3293 target_mourn_inferior (cs.last_ptid);
3297 /* Attach to a new program. */
3298 static void
3299 handle_v_attach (char *own_buf)
3301 client_state &cs = get_client_state ();
3303 int pid = strtol (own_buf + 8, NULL, 16);
3307 if (attach_inferior (pid) == 0)
3309 /* Don't report shared library events after attaching, even if
3310 some libraries are preloaded. GDB will always poll the
3311 library list. Avoids the "stopped by shared library event"
3312 notice on the GDB side. */
3313 current_process ()->dlls_changed = false;
3315 if (non_stop)
3317 /* In non-stop, we don't send a resume reply. Stop events
3318 will follow up using the normal notification
3319 mechanism. */
3320 write_ok (own_buf);
3322 else
3323 prepare_resume_reply (own_buf, cs.last_ptid, cs.last_status);
3325 else
3327 /* Not supported. */
3328 own_buf[0] = 0;
3331 catch (const gdb_exception_error &exception)
3333 sprintf (own_buf, "E.%s", exception.what ());
3337 /* Decode an argument from the vRun packet buffer. PTR points to the
3338 first hex-encoded character in the buffer, and LEN is the number of
3339 characters to read from the packet buffer.
3341 If the argument decoding is successful, return a buffer containing the
3342 decoded argument, including a null terminator at the end.
3344 If the argument decoding fails for any reason, return nullptr. */
3346 static gdb::unique_xmalloc_ptr<char>
3347 decode_v_run_arg (const char *ptr, size_t len)
3349 /* Two hex characters are required for each decoded byte. */
3350 if (len % 2 != 0)
3351 return nullptr;
3353 /* The length in bytes needed for the decoded argument. */
3354 len /= 2;
3356 /* Buffer to decode the argument into. The '+ 1' is for the null
3357 terminator we will add. */
3358 char *arg = (char *) xmalloc (len + 1);
3360 /* Decode the argument from the packet and add a null terminator. We do
3361 this within a try block as invalid characters within the PTR buffer
3362 will cause hex2bin to throw an exception. Our caller relies on us
3363 returning nullptr in order to clean up some memory allocations. */
3366 hex2bin (ptr, (gdb_byte *) arg, len);
3367 arg[len] = '\0';
3369 catch (const gdb_exception_error &exception)
3371 return nullptr;
3374 return gdb::unique_xmalloc_ptr<char> (arg);
3377 /* Run a new program. */
3378 static void
3379 handle_v_run (char *own_buf)
3381 client_state &cs = get_client_state ();
3382 char *p, *next_p;
3383 std::vector<char *> new_argv;
3384 gdb::unique_xmalloc_ptr<char> new_program_name;
3385 int i;
3387 for (i = 0, p = own_buf + strlen ("vRun;");
3388 /* Exit condition is at the end of the loop. */;
3389 p = next_p + 1, ++i)
3391 next_p = strchr (p, ';');
3392 if (next_p == NULL)
3393 next_p = p + strlen (p);
3395 if (i == 0 && p == next_p)
3397 /* No program specified. */
3398 gdb_assert (new_program_name == nullptr);
3400 else if (p == next_p)
3402 /* Empty argument. */
3403 new_argv.push_back (xstrdup (""));
3405 else
3407 /* The length of the argument string in the packet. */
3408 size_t len = next_p - p;
3410 gdb::unique_xmalloc_ptr<char> arg = decode_v_run_arg (p, len);
3411 if (arg == nullptr)
3413 write_enn (own_buf);
3414 free_vector_argv (new_argv);
3415 return;
3418 if (i == 0)
3419 new_program_name = std::move (arg);
3420 else
3421 new_argv.push_back (arg.release ());
3423 if (*next_p == '\0')
3424 break;
3427 if (new_program_name == nullptr)
3429 /* GDB didn't specify a program to run. Use the program from the
3430 last run with the new argument list. */
3431 if (program_path.get () == nullptr)
3433 write_enn (own_buf);
3434 free_vector_argv (new_argv);
3435 return;
3438 else
3439 program_path.set (new_program_name.get ());
3441 /* Free the old argv and install the new one. */
3442 free_vector_argv (program_args);
3443 program_args = new_argv;
3447 target_create_inferior (program_path.get (), program_args);
3449 catch (const gdb_exception_error &exception)
3451 sprintf (own_buf, "E.%s", exception.what ());
3452 return;
3455 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
3457 prepare_resume_reply (own_buf, cs.last_ptid, cs.last_status);
3459 /* In non-stop, sending a resume reply doesn't set the general
3460 thread, but GDB assumes a vRun sets it (this is so GDB can
3461 query which is the main thread of the new inferior. */
3462 if (non_stop)
3463 cs.general_thread = cs.last_ptid;
3465 else
3466 write_enn (own_buf);
3469 /* Kill process. */
3470 static void
3471 handle_v_kill (char *own_buf)
3473 client_state &cs = get_client_state ();
3474 int pid;
3475 char *p = &own_buf[6];
3476 if (cs.multi_process)
3477 pid = strtol (p, NULL, 16);
3478 else
3479 pid = signal_pid;
3481 process_info *proc = find_process_pid (pid);
3483 if (proc != nullptr && kill_inferior (proc) == 0)
3485 cs.last_status.set_signalled (GDB_SIGNAL_KILL);
3486 cs.last_ptid = ptid_t (pid);
3487 discard_queued_stop_replies (cs.last_ptid);
3488 write_ok (own_buf);
3490 else
3491 write_enn (own_buf);
3494 /* Handle all of the extended 'v' packets. */
3495 void
3496 handle_v_requests (char *own_buf, int packet_len, int *new_packet_len)
3498 client_state &cs = get_client_state ();
3499 if (!disable_packet_vCont)
3501 if (strcmp (own_buf, "vCtrlC") == 0)
3503 the_target->request_interrupt ();
3504 write_ok (own_buf);
3505 return;
3508 if (startswith (own_buf, "vCont;"))
3510 handle_v_cont (own_buf);
3511 return;
3514 if (startswith (own_buf, "vCont?"))
3516 strcpy (own_buf, "vCont;c;C;t");
3518 if (target_supports_hardware_single_step ()
3519 || target_supports_software_single_step ()
3520 || !cs.vCont_supported)
3522 /* If target supports single step either by hardware or by
3523 software, add actions s and S to the list of supported
3524 actions. On the other hand, if GDB doesn't request the
3525 supported vCont actions in qSupported packet, add s and
3526 S to the list too. */
3527 own_buf = own_buf + strlen (own_buf);
3528 strcpy (own_buf, ";s;S");
3531 if (target_supports_range_stepping ())
3533 own_buf = own_buf + strlen (own_buf);
3534 strcpy (own_buf, ";r");
3536 return;
3540 if (startswith (own_buf, "vFile:")
3541 && handle_vFile (own_buf, packet_len, new_packet_len))
3542 return;
3544 if (startswith (own_buf, "vAttach;"))
3546 if ((!extended_protocol || !cs.multi_process) && target_running ())
3548 fprintf (stderr, "Already debugging a process\n");
3549 write_enn (own_buf);
3550 return;
3552 handle_v_attach (own_buf);
3553 return;
3556 if (startswith (own_buf, "vRun;"))
3558 if ((!extended_protocol || !cs.multi_process) && target_running ())
3560 fprintf (stderr, "Already debugging a process\n");
3561 write_enn (own_buf);
3562 return;
3564 handle_v_run (own_buf);
3565 return;
3568 if (startswith (own_buf, "vKill;"))
3570 if (!target_running ())
3572 fprintf (stderr, "No process to kill\n");
3573 write_enn (own_buf);
3574 return;
3576 handle_v_kill (own_buf);
3577 return;
3580 if (handle_notif_ack (own_buf, packet_len))
3581 return;
3583 /* Otherwise we didn't know what packet it was. Say we didn't
3584 understand it. */
3585 own_buf[0] = 0;
3586 return;
3589 /* Resume thread and wait for another event. In non-stop mode,
3590 don't really wait here, but return immediately to the event
3591 loop. */
3592 static void
3593 myresume (char *own_buf, int step, int sig)
3595 client_state &cs = get_client_state ();
3596 struct thread_resume resume_info[2];
3597 int n = 0;
3598 int valid_cont_thread;
3600 valid_cont_thread = (cs.cont_thread != null_ptid
3601 && cs.cont_thread != minus_one_ptid);
3603 if (step || sig || valid_cont_thread)
3605 resume_info[0].thread = current_ptid;
3606 if (step)
3607 resume_info[0].kind = resume_step;
3608 else
3609 resume_info[0].kind = resume_continue;
3610 resume_info[0].sig = sig;
3611 n++;
3614 if (!valid_cont_thread)
3616 resume_info[n].thread = minus_one_ptid;
3617 resume_info[n].kind = resume_continue;
3618 resume_info[n].sig = 0;
3619 n++;
3622 resume (resume_info, n);
3625 /* Callback for for_each_thread. Make a new stop reply for each
3626 stopped thread. */
3628 static void
3629 queue_stop_reply_callback (thread_info *thread)
3631 /* For now, assume targets that don't have this callback also don't
3632 manage the thread's last_status field. */
3633 if (!the_target->supports_thread_stopped ())
3635 struct vstop_notif *new_notif = new struct vstop_notif;
3637 new_notif->ptid = thread->id;
3638 new_notif->status = thread->last_status;
3639 /* Pass the last stop reply back to GDB, but don't notify
3640 yet. */
3641 notif_event_enque (&notif_stop, new_notif);
3643 else
3645 if (target_thread_stopped (thread))
3647 threads_debug_printf
3648 ("Reporting thread %s as already stopped with %s",
3649 target_pid_to_str (thread->id).c_str (),
3650 thread->last_status.to_string ().c_str ());
3652 gdb_assert (thread->last_status.kind () != TARGET_WAITKIND_IGNORE);
3654 /* Pass the last stop reply back to GDB, but don't notify
3655 yet. */
3656 queue_stop_reply (thread->id, thread->last_status);
3661 /* Set this inferior threads's state as "want-stopped". We won't
3662 resume this thread until the client gives us another action for
3663 it. */
3665 static void
3666 gdb_wants_thread_stopped (thread_info *thread)
3668 thread->last_resume_kind = resume_stop;
3670 if (thread->last_status.kind () == TARGET_WAITKIND_IGNORE)
3672 /* Most threads are stopped implicitly (all-stop); tag that with
3673 signal 0. */
3674 thread->last_status.set_stopped (GDB_SIGNAL_0);
3678 /* Set all threads' states as "want-stopped". */
3680 static void
3681 gdb_wants_all_threads_stopped (void)
3683 for_each_thread (gdb_wants_thread_stopped);
3686 /* Callback for for_each_thread. If the thread is stopped with an
3687 interesting event, mark it as having a pending event. */
3689 static void
3690 set_pending_status_callback (thread_info *thread)
3692 if (thread->last_status.kind () != TARGET_WAITKIND_STOPPED
3693 || (thread->last_status.sig () != GDB_SIGNAL_0
3694 /* A breakpoint, watchpoint or finished step from a previous
3695 GDB run isn't considered interesting for a new GDB run.
3696 If we left those pending, the new GDB could consider them
3697 random SIGTRAPs. This leaves out real async traps. We'd
3698 have to peek into the (target-specific) siginfo to
3699 distinguish those. */
3700 && thread->last_status.sig () != GDB_SIGNAL_TRAP))
3701 thread->status_pending_p = 1;
3704 /* Status handler for the '?' packet. */
3706 static void
3707 handle_status (char *own_buf)
3709 client_state &cs = get_client_state ();
3711 /* GDB is connected, don't forward events to the target anymore. */
3712 for_each_process ([] (process_info *process) {
3713 process->gdb_detached = 0;
3716 /* In non-stop mode, we must send a stop reply for each stopped
3717 thread. In all-stop mode, just send one for the first stopped
3718 thread we find. */
3720 if (non_stop)
3722 for_each_thread (queue_stop_reply_callback);
3724 /* The first is sent immediatly. OK is sent if there is no
3725 stopped thread, which is the same handling of the vStopped
3726 packet (by design). */
3727 notif_write_event (&notif_stop, cs.own_buf);
3729 else
3731 thread_info *thread = NULL;
3733 target_pause_all (false);
3734 target_stabilize_threads ();
3735 gdb_wants_all_threads_stopped ();
3737 /* We can only report one status, but we might be coming out of
3738 non-stop -- if more than one thread is stopped with
3739 interesting events, leave events for the threads we're not
3740 reporting now pending. They'll be reported the next time the
3741 threads are resumed. Start by marking all interesting events
3742 as pending. */
3743 for_each_thread (set_pending_status_callback);
3745 /* Prefer the last thread that reported an event to GDB (even if
3746 that was a GDB_SIGNAL_TRAP). */
3747 if (cs.last_status.kind () != TARGET_WAITKIND_IGNORE
3748 && cs.last_status.kind () != TARGET_WAITKIND_EXITED
3749 && cs.last_status.kind () != TARGET_WAITKIND_SIGNALLED)
3750 thread = find_thread_ptid (cs.last_ptid);
3752 /* If the last event thread is not found for some reason, look
3753 for some other thread that might have an event to report. */
3754 if (thread == NULL)
3755 thread = find_thread ([] (thread_info *thr_arg)
3757 return thr_arg->status_pending_p;
3760 /* If we're still out of luck, simply pick the first thread in
3761 the thread list. */
3762 if (thread == NULL)
3763 thread = get_first_thread ();
3765 if (thread != NULL)
3767 struct thread_info *tp = (struct thread_info *) thread;
3769 /* We're reporting this event, so it's no longer
3770 pending. */
3771 tp->status_pending_p = 0;
3773 /* GDB assumes the current thread is the thread we're
3774 reporting the status for. */
3775 cs.general_thread = thread->id;
3776 set_desired_thread ();
3778 gdb_assert (tp->last_status.kind () != TARGET_WAITKIND_IGNORE);
3779 prepare_resume_reply (own_buf, tp->id, tp->last_status);
3781 else
3782 strcpy (own_buf, "W00");
3786 static void
3787 gdbserver_version (void)
3789 printf ("GNU gdbserver %s%s\n"
3790 "Copyright (C) 2024 Free Software Foundation, Inc.\n"
3791 "gdbserver is free software, covered by the "
3792 "GNU General Public License.\n"
3793 "This gdbserver was configured as \"%s\"\n",
3794 PKGVERSION, version, host_name);
3797 static void
3798 gdbserver_usage (FILE *stream)
3800 fprintf (stream, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3801 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3802 "\tgdbserver [OPTIONS] --multi COMM\n"
3803 "\n"
3804 "COMM may either be a tty device (for serial debugging),\n"
3805 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3806 "stdin/stdout of gdbserver.\n"
3807 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3808 "PID is the process ID to attach to, when --attach is specified.\n"
3809 "\n"
3810 "Operating modes:\n"
3811 "\n"
3812 " --attach Attach to running process PID.\n"
3813 " --multi Start server without a specific program, and\n"
3814 " only quit when explicitly commanded.\n"
3815 " --once Exit after the first connection has closed.\n"
3816 " --help Print this message and then exit.\n"
3817 " --version Display version information and exit.\n"
3818 "\n"
3819 "Other options:\n"
3820 "\n"
3821 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3822 " --disable-randomization\n"
3823 " Run PROG with address space randomization disabled.\n"
3824 " --no-disable-randomization\n"
3825 " Don't disable address space randomization when\n"
3826 " starting PROG.\n"
3827 " --startup-with-shell\n"
3828 " Start PROG using a shell. I.e., execs a shell that\n"
3829 " then execs PROG. (default)\n"
3830 " --no-startup-with-shell\n"
3831 " Exec PROG directly instead of using a shell.\n"
3832 " Disables argument globbing and variable substitution\n"
3833 " on UNIX-like systems.\n"
3834 "\n"
3835 "Debug options:\n"
3836 "\n"
3837 " --debug[=OPT1,OPT2,...]\n"
3838 " Enable debugging output.\n"
3839 " Options:\n"
3840 " all, threads, event-loop, remote\n"
3841 " With no options, 'threads' is assumed.\n"
3842 " Prefix an option with '-' to disable\n"
3843 " debugging of that component.\n"
3844 " --debug-format=OPT1[,OPT2,...]\n"
3845 " Specify extra content in debugging output.\n"
3846 " Options:\n"
3847 " all\n"
3848 " none\n"
3849 " timestamp\n"
3850 " --disable-packet=OPT1[,OPT2,...]\n"
3851 " Disable support for RSP packets or features.\n"
3852 " Options:\n"
3853 " vCont, T, Tthread, qC, qfThreadInfo and \n"
3854 " threads (disable all threading packets).\n"
3855 "\n"
3856 "For more information, consult the GDB manual (available as on-line \n"
3857 "info or a printed manual).\n");
3858 if (REPORT_BUGS_TO[0] && stream == stdout)
3859 fprintf (stream, "Report bugs to \"%s\".\n", REPORT_BUGS_TO);
3862 static void
3863 gdbserver_show_disableable (FILE *stream)
3865 fprintf (stream, "Disableable packets:\n"
3866 " vCont \tAll vCont packets\n"
3867 " qC \tQuerying the current thread\n"
3868 " qfThreadInfo\tThread listing\n"
3869 " Tthread \tPassing the thread specifier in the "
3870 "T stop reply packet\n"
3871 " threads \tAll of the above\n"
3872 " T \tAll 'T' packets\n");
3875 /* Start up the event loop. This is the entry point to the event
3876 loop. */
3878 static void
3879 start_event_loop ()
3881 /* Loop until there is nothing to do. This is the entry point to
3882 the event loop engine. If nothing is ready at this time, wait
3883 for something to happen (via wait_for_event), then process it.
3884 Return when there are no longer event sources to wait for. */
3886 keep_processing_events = true;
3887 while (keep_processing_events)
3889 /* Any events already waiting in the queue? */
3890 int res = gdb_do_one_event ();
3892 /* Was there an error? */
3893 if (res == -1)
3894 break;
3897 /* We are done with the event loop. There are no more event sources
3898 to listen to. So we exit gdbserver. */
3901 static void
3902 kill_inferior_callback (process_info *process)
3904 kill_inferior (process);
3905 discard_queued_stop_replies (ptid_t (process->pid));
3908 /* Call this when exiting gdbserver with possible inferiors that need
3909 to be killed or detached from. */
3911 static void
3912 detach_or_kill_for_exit (void)
3914 /* First print a list of the inferiors we will be killing/detaching.
3915 This is to assist the user, for example, in case the inferior unexpectedly
3916 dies after we exit: did we screw up or did the inferior exit on its own?
3917 Having this info will save some head-scratching. */
3919 if (have_started_inferiors_p ())
3921 fprintf (stderr, "Killing process(es):");
3923 for_each_process ([] (process_info *process) {
3924 if (!process->attached)
3925 fprintf (stderr, " %d", process->pid);
3928 fprintf (stderr, "\n");
3930 if (have_attached_inferiors_p ())
3932 fprintf (stderr, "Detaching process(es):");
3934 for_each_process ([] (process_info *process) {
3935 if (process->attached)
3936 fprintf (stderr, " %d", process->pid);
3939 fprintf (stderr, "\n");
3942 /* Now we can kill or detach the inferiors. */
3943 for_each_process ([] (process_info *process) {
3944 int pid = process->pid;
3946 if (process->attached)
3947 detach_inferior (process);
3948 else
3949 kill_inferior (process);
3951 discard_queued_stop_replies (ptid_t (pid));
3955 /* Value that will be passed to exit(3) when gdbserver exits. */
3956 static int exit_code;
3958 /* Wrapper for detach_or_kill_for_exit that catches and prints
3959 errors. */
3961 static void
3962 detach_or_kill_for_exit_cleanup ()
3966 detach_or_kill_for_exit ();
3968 catch (const gdb_exception &exception)
3970 fflush (stdout);
3971 fprintf (stderr, "Detach or kill failed: %s\n",
3972 exception.what ());
3973 exit_code = 1;
3977 #if GDB_SELF_TEST
3979 namespace selftests {
3981 static void
3982 test_memory_tagging_functions (void)
3984 /* Setup testing. */
3985 gdb::char_vector packet;
3986 gdb::byte_vector tags, bv;
3987 std::string expected;
3988 packet.resize (32000);
3989 CORE_ADDR addr;
3990 size_t len;
3991 int type;
3993 /* Test parsing a qMemTags request. */
3995 /* Valid request, addr, len and type updated. */
3996 addr = 0xff;
3997 len = 255;
3998 type = 255;
3999 strcpy (packet.data (), "qMemTags:0,0:0");
4000 parse_fetch_memtags_request (packet.data (), &addr, &len, &type);
4001 SELF_CHECK (addr == 0 && len == 0 && type == 0);
4003 /* Valid request, addr, len and type updated. */
4004 addr = 0;
4005 len = 0;
4006 type = 0;
4007 strcpy (packet.data (), "qMemTags:deadbeef,ff:5");
4008 parse_fetch_memtags_request (packet.data (), &addr, &len, &type);
4009 SELF_CHECK (addr == 0xdeadbeef && len == 255 && type == 5);
4011 /* Test creating a qMemTags reply. */
4013 /* Non-empty tag data. */
4014 bv.resize (0);
4016 for (int i = 0; i < 5; i++)
4017 bv.push_back (i);
4019 expected = "m0001020304";
4020 SELF_CHECK (create_fetch_memtags_reply (packet.data (), bv) == true);
4021 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
4023 /* Test parsing a QMemTags request. */
4025 /* Valid request and empty tag data: addr, len, type and tags updated. */
4026 addr = 0xff;
4027 len = 255;
4028 type = 255;
4029 tags.resize (5);
4030 strcpy (packet.data (), "QMemTags:0,0:0:");
4031 SELF_CHECK (parse_store_memtags_request (packet.data (),
4032 &addr, &len, tags, &type) == true);
4033 SELF_CHECK (addr == 0 && len == 0 && type == 0 && tags.size () == 0);
4035 /* Valid request and non-empty tag data: addr, len, type
4036 and tags updated. */
4037 addr = 0;
4038 len = 0;
4039 type = 0;
4040 tags.resize (0);
4041 strcpy (packet.data (),
4042 "QMemTags:deadbeef,ff:5:0001020304");
4043 SELF_CHECK (parse_store_memtags_request (packet.data (), &addr, &len, tags,
4044 &type) == true);
4045 SELF_CHECK (addr == 0xdeadbeef && len == 255 && type == 5
4046 && tags.size () == 5);
4049 } // namespace selftests
4050 #endif /* GDB_SELF_TEST */
4052 /* Main function. This is called by the real "main" function,
4053 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
4055 [[noreturn]] static void
4056 captured_main (int argc, char *argv[])
4058 int bad_attach;
4059 int pid;
4060 char *arg_end;
4061 const char *port = NULL;
4062 char **next_arg = &argv[1];
4063 volatile int multi_mode = 0;
4064 volatile int attach = 0;
4065 int was_running;
4066 bool selftest = false;
4067 #if GDB_SELF_TEST
4068 std::vector<const char *> selftest_filters;
4070 selftests::register_test ("remote_memory_tagging",
4071 selftests::test_memory_tagging_functions);
4072 #endif
4074 current_directory = getcwd (NULL, 0);
4075 client_state &cs = get_client_state ();
4077 if (current_directory == NULL)
4079 error (_("Could not find current working directory: %s"),
4080 safe_strerror (errno));
4083 while (*next_arg != NULL && **next_arg == '-')
4085 if (strcmp (*next_arg, "--version") == 0)
4087 gdbserver_version ();
4088 exit (0);
4090 else if (strcmp (*next_arg, "--help") == 0)
4092 gdbserver_usage (stdout);
4093 exit (0);
4095 else if (strcmp (*next_arg, "--attach") == 0)
4096 attach = 1;
4097 else if (strcmp (*next_arg, "--multi") == 0)
4098 multi_mode = 1;
4099 else if (strcmp (*next_arg, "--wrapper") == 0)
4101 char **tmp;
4103 next_arg++;
4105 tmp = next_arg;
4106 while (*next_arg != NULL && strcmp (*next_arg, "--") != 0)
4108 wrapper_argv += *next_arg;
4109 wrapper_argv += ' ';
4110 next_arg++;
4113 if (!wrapper_argv.empty ())
4115 /* Erase the last whitespace. */
4116 wrapper_argv.erase (wrapper_argv.end () - 1);
4119 if (next_arg == tmp || *next_arg == NULL)
4121 gdbserver_usage (stderr);
4122 exit (1);
4125 /* Consume the "--". */
4126 *next_arg = NULL;
4128 else if (startswith (*next_arg, "--debug="))
4132 parse_debug_options ((*next_arg) + sizeof ("--debug=") - 1);
4134 catch (const gdb_exception_error &exception)
4136 fflush (stdout);
4137 fprintf (stderr, "gdbserver: %s\n", exception.what ());
4138 exit (1);
4141 else if (strcmp (*next_arg, "--debug") == 0)
4145 parse_debug_options ("");
4147 catch (const gdb_exception_error &exception)
4149 fflush (stdout);
4150 fprintf (stderr, "gdbserver: %s\n", exception.what ());
4151 exit (1);
4154 else if (startswith (*next_arg, "--debug-format="))
4156 std::string error_msg
4157 = parse_debug_format_options ((*next_arg)
4158 + sizeof ("--debug-format=") - 1, 0);
4160 if (!error_msg.empty ())
4162 fprintf (stderr, "%s", error_msg.c_str ());
4163 exit (1);
4166 else if (startswith (*next_arg, "--debug-file="))
4167 debug_set_output ((*next_arg) + sizeof ("--debug-file=") -1);
4168 else if (strcmp (*next_arg, "--disable-packet") == 0)
4170 gdbserver_show_disableable (stdout);
4171 exit (0);
4173 else if (startswith (*next_arg, "--disable-packet="))
4175 char *packets = *next_arg += sizeof ("--disable-packet=") - 1;
4176 char *saveptr;
4177 for (char *tok = strtok_r (packets, ",", &saveptr);
4178 tok != NULL;
4179 tok = strtok_r (NULL, ",", &saveptr))
4181 if (strcmp ("vCont", tok) == 0)
4182 disable_packet_vCont = true;
4183 else if (strcmp ("Tthread", tok) == 0)
4184 disable_packet_Tthread = true;
4185 else if (strcmp ("qC", tok) == 0)
4186 disable_packet_qC = true;
4187 else if (strcmp ("qfThreadInfo", tok) == 0)
4188 disable_packet_qfThreadInfo = true;
4189 else if (strcmp ("T", tok) == 0)
4190 disable_packet_T = true;
4191 else if (strcmp ("threads", tok) == 0)
4193 disable_packet_vCont = true;
4194 disable_packet_Tthread = true;
4195 disable_packet_qC = true;
4196 disable_packet_qfThreadInfo = true;
4198 else
4200 fprintf (stderr, "Don't know how to disable \"%s\".\n\n",
4201 tok);
4202 gdbserver_show_disableable (stderr);
4203 exit (1);
4207 else if (strcmp (*next_arg, "-") == 0)
4209 /* "-" specifies a stdio connection and is a form of port
4210 specification. */
4211 port = STDIO_CONNECTION_NAME;
4213 /* Implying --once here prevents a hang after stdin has been closed. */
4214 run_once = true;
4216 next_arg++;
4217 break;
4219 else if (strcmp (*next_arg, "--disable-randomization") == 0)
4220 cs.disable_randomization = 1;
4221 else if (strcmp (*next_arg, "--no-disable-randomization") == 0)
4222 cs.disable_randomization = 0;
4223 else if (strcmp (*next_arg, "--startup-with-shell") == 0)
4224 startup_with_shell = true;
4225 else if (strcmp (*next_arg, "--no-startup-with-shell") == 0)
4226 startup_with_shell = false;
4227 else if (strcmp (*next_arg, "--once") == 0)
4228 run_once = true;
4229 else if (strcmp (*next_arg, "--selftest") == 0)
4230 selftest = true;
4231 else if (startswith (*next_arg, "--selftest="))
4233 selftest = true;
4235 #if GDB_SELF_TEST
4236 const char *filter = *next_arg + strlen ("--selftest=");
4237 if (*filter == '\0')
4239 fprintf (stderr, _("Error: selftest filter is empty.\n"));
4240 exit (1);
4243 selftest_filters.push_back (filter);
4244 #endif
4246 else
4248 fprintf (stderr, "Unknown argument: %s\n", *next_arg);
4249 exit (1);
4252 next_arg++;
4253 continue;
4256 if (port == NULL)
4258 port = *next_arg;
4259 next_arg++;
4261 if ((port == NULL || (!attach && !multi_mode && *next_arg == NULL))
4262 && !selftest)
4264 gdbserver_usage (stderr);
4265 exit (1);
4268 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
4269 opened by remote_prepare. */
4270 notice_open_fds ();
4272 save_original_signals_state (false);
4274 /* We need to know whether the remote connection is stdio before
4275 starting the inferior. Inferiors created in this scenario have
4276 stdin,stdout redirected. So do this here before we call
4277 start_inferior. */
4278 if (port != NULL)
4279 remote_prepare (port);
4281 bad_attach = 0;
4282 pid = 0;
4284 /* --attach used to come after PORT, so allow it there for
4285 compatibility. */
4286 if (*next_arg != NULL && strcmp (*next_arg, "--attach") == 0)
4288 attach = 1;
4289 next_arg++;
4292 if (attach
4293 && (*next_arg == NULL
4294 || (*next_arg)[0] == '\0'
4295 || (pid = strtoul (*next_arg, &arg_end, 0)) == 0
4296 || *arg_end != '\0'
4297 || next_arg[1] != NULL))
4298 bad_attach = 1;
4300 if (bad_attach)
4302 gdbserver_usage (stderr);
4303 exit (1);
4306 /* Gather information about the environment. */
4307 our_environ = gdb_environ::from_host_environ ();
4309 initialize_async_io ();
4310 initialize_low ();
4311 have_job_control ();
4312 if (target_supports_tracepoints ())
4313 initialize_tracepoint ();
4315 mem_buf = (unsigned char *) xmalloc (PBUFSIZ);
4317 if (selftest)
4319 #if GDB_SELF_TEST
4320 selftests::run_tests (selftest_filters);
4321 #else
4322 printf (_("Selftests have been disabled for this build.\n"));
4323 #endif
4324 throw_quit ("Quit");
4327 if (pid == 0 && *next_arg != NULL)
4329 int i, n;
4331 n = argc - (next_arg - argv);
4332 program_path.set (next_arg[0]);
4333 for (i = 1; i < n; i++)
4334 program_args.push_back (xstrdup (next_arg[i]));
4336 /* Wait till we are at first instruction in program. */
4337 target_create_inferior (program_path.get (), program_args);
4339 /* We are now (hopefully) stopped at the first instruction of
4340 the target process. This assumes that the target process was
4341 successfully created. */
4343 else if (pid != 0)
4345 if (attach_inferior (pid) == -1)
4346 error ("Attaching not supported on this target");
4348 /* Otherwise succeeded. */
4350 else
4352 cs.last_status.set_exited (0);
4353 cs.last_ptid = minus_one_ptid;
4356 SCOPE_EXIT { detach_or_kill_for_exit_cleanup (); };
4358 /* Don't report shared library events on the initial connection,
4359 even if some libraries are preloaded. Avoids the "stopped by
4360 shared library event" notice on gdb side. */
4361 if (current_thread != nullptr)
4362 current_process ()->dlls_changed = false;
4364 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
4365 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
4366 was_running = 0;
4367 else
4368 was_running = 1;
4370 if (!was_running && !multi_mode)
4371 error ("No program to debug");
4373 while (1)
4375 cs.noack_mode = 0;
4376 cs.multi_process = 0;
4377 cs.report_fork_events = 0;
4378 cs.report_vfork_events = 0;
4379 cs.report_exec_events = 0;
4380 /* Be sure we're out of tfind mode. */
4381 cs.current_traceframe = -1;
4382 cs.cont_thread = null_ptid;
4383 cs.swbreak_feature = 0;
4384 cs.hwbreak_feature = 0;
4385 cs.vCont_supported = 0;
4386 cs.memory_tagging_feature = false;
4387 cs.error_message_supported = false;
4389 remote_open (port);
4393 /* Wait for events. This will return when all event sources
4394 are removed from the event loop. */
4395 start_event_loop ();
4397 /* If an exit was requested (using the "monitor exit"
4398 command), terminate now. */
4399 if (exit_requested)
4400 throw_quit ("Quit");
4402 /* The only other way to get here is for getpkt to fail:
4404 - If --once was specified, we're done.
4406 - If not in extended-remote mode, and we're no longer
4407 debugging anything, simply exit: GDB has disconnected
4408 after processing the last process exit.
4410 - Otherwise, close the connection and reopen it at the
4411 top of the loop. */
4412 if (run_once || (!extended_protocol && !target_running ()))
4413 throw_quit ("Quit");
4415 fprintf (stderr,
4416 "Remote side has terminated connection. "
4417 "GDBserver will reopen the connection.\n");
4419 /* Get rid of any pending statuses. An eventual reconnection
4420 (by the same GDB instance or another) will refresh all its
4421 state from scratch. */
4422 discard_queued_stop_replies (minus_one_ptid);
4423 for_each_thread ([] (thread_info *thread)
4425 thread->status_pending_p = 0;
4428 if (tracing)
4430 if (disconnected_tracing)
4432 /* Try to enable non-stop/async mode, so we we can
4433 both wait for an async socket accept, and handle
4434 async target events simultaneously. There's also
4435 no point either in having the target always stop
4436 all threads, when we're going to pass signals
4437 down without informing GDB. */
4438 if (!non_stop)
4440 if (the_target->start_non_stop (true))
4441 non_stop = 1;
4443 /* Detaching implicitly resumes all threads;
4444 simply disconnecting does not. */
4447 else
4449 fprintf (stderr,
4450 "Disconnected tracing disabled; "
4451 "stopping trace run.\n");
4452 stop_tracing ();
4456 catch (const gdb_exception_error &exception)
4458 fflush (stdout);
4459 fprintf (stderr, "gdbserver: %s\n", exception.what ());
4461 if (response_needed)
4463 write_enn (cs.own_buf);
4464 putpkt (cs.own_buf);
4467 if (run_once)
4468 throw_quit ("Quit");
4473 /* Main function. */
4476 main (int argc, char *argv[])
4478 setlocale (LC_CTYPE, "");
4482 captured_main (argc, argv);
4484 catch (const gdb_exception &exception)
4486 if (exception.reason == RETURN_ERROR)
4488 fflush (stdout);
4489 fprintf (stderr, "%s\n", exception.what ());
4490 fprintf (stderr, "Exiting\n");
4491 exit_code = 1;
4494 exit (exit_code);
4497 gdb_assert_not_reached ("captured_main should never return");
4500 /* Process options coming from Z packets for a breakpoint. PACKET is
4501 the packet buffer. *PACKET is updated to point to the first char
4502 after the last processed option. */
4504 static void
4505 process_point_options (struct gdb_breakpoint *bp, const char **packet)
4507 const char *dataptr = *packet;
4508 int persist;
4510 /* Check if data has the correct format. */
4511 if (*dataptr != ';')
4512 return;
4514 dataptr++;
4516 while (*dataptr)
4518 if (*dataptr == ';')
4519 ++dataptr;
4521 if (*dataptr == 'X')
4523 /* Conditional expression. */
4524 threads_debug_printf ("Found breakpoint condition.");
4525 if (!add_breakpoint_condition (bp, &dataptr))
4526 dataptr = strchrnul (dataptr, ';');
4528 else if (startswith (dataptr, "cmds:"))
4530 dataptr += strlen ("cmds:");
4531 threads_debug_printf ("Found breakpoint commands %s.", dataptr);
4532 persist = (*dataptr == '1');
4533 dataptr += 2;
4534 if (add_breakpoint_commands (bp, &dataptr, persist))
4535 dataptr = strchrnul (dataptr, ';');
4537 else
4539 fprintf (stderr, "Unknown token %c, ignoring.\n",
4540 *dataptr);
4541 /* Skip tokens until we find one that we recognize. */
4542 dataptr = strchrnul (dataptr, ';');
4545 *packet = dataptr;
4548 /* Event loop callback that handles a serial event. The first byte in
4549 the serial buffer gets us here. We expect characters to arrive at
4550 a brisk pace, so we read the rest of the packet with a blocking
4551 getpkt call. */
4553 static int
4554 process_serial_event (void)
4556 client_state &cs = get_client_state ();
4557 int signal;
4558 unsigned int len;
4559 CORE_ADDR mem_addr;
4560 unsigned char sig;
4561 int packet_len;
4562 int new_packet_len = -1;
4564 disable_async_io ();
4566 response_needed = false;
4567 packet_len = getpkt (cs.own_buf);
4568 if (packet_len <= 0)
4570 remote_close ();
4571 /* Force an event loop break. */
4572 return -1;
4574 response_needed = true;
4576 char ch = cs.own_buf[0];
4577 switch (ch)
4579 case 'q':
4580 handle_query (cs.own_buf, packet_len, &new_packet_len);
4581 break;
4582 case 'Q':
4583 handle_general_set (cs.own_buf);
4584 break;
4585 case 'D':
4586 handle_detach (cs.own_buf);
4587 break;
4588 case '!':
4589 extended_protocol = true;
4590 write_ok (cs.own_buf);
4591 break;
4592 case '?':
4593 handle_status (cs.own_buf);
4594 break;
4595 case 'H':
4596 if (cs.own_buf[1] == 'c' || cs.own_buf[1] == 'g' || cs.own_buf[1] == 's')
4598 require_running_or_break (cs.own_buf);
4600 ptid_t thread_id = read_ptid (&cs.own_buf[2], NULL);
4602 if (thread_id == null_ptid || thread_id == minus_one_ptid)
4603 thread_id = null_ptid;
4604 else if (thread_id.is_pid ())
4606 /* The ptid represents a pid. */
4607 thread_info *thread = find_any_thread_of_pid (thread_id.pid ());
4609 if (thread == NULL)
4611 write_enn (cs.own_buf);
4612 break;
4615 thread_id = thread->id;
4617 else
4619 /* The ptid represents a lwp/tid. */
4620 if (find_thread_ptid (thread_id) == NULL)
4622 write_enn (cs.own_buf);
4623 break;
4627 if (cs.own_buf[1] == 'g')
4629 if (thread_id == null_ptid)
4631 /* GDB is telling us to choose any thread. Check if
4632 the currently selected thread is still valid. If
4633 it is not, select the first available. */
4634 thread_info *thread = find_thread_ptid (cs.general_thread);
4635 if (thread == NULL)
4636 thread = get_first_thread ();
4637 thread_id = thread->id;
4640 cs.general_thread = thread_id;
4641 set_desired_thread ();
4642 gdb_assert (current_thread != NULL);
4644 else if (cs.own_buf[1] == 'c')
4645 cs.cont_thread = thread_id;
4647 write_ok (cs.own_buf);
4649 else
4651 /* Silently ignore it so that gdb can extend the protocol
4652 without compatibility headaches. */
4653 cs.own_buf[0] = '\0';
4655 break;
4656 case 'g':
4657 require_running_or_break (cs.own_buf);
4658 if (cs.current_traceframe >= 0)
4660 struct regcache *regcache
4661 = new_register_cache (current_target_desc ());
4663 if (fetch_traceframe_registers (cs.current_traceframe,
4664 regcache, -1) == 0)
4665 registers_to_string (regcache, cs.own_buf);
4666 else
4667 write_enn (cs.own_buf);
4668 free_register_cache (regcache);
4670 else
4672 struct regcache *regcache;
4674 if (!set_desired_thread ())
4675 write_enn (cs.own_buf);
4676 else
4678 regcache = get_thread_regcache (current_thread, 1);
4679 registers_to_string (regcache, cs.own_buf);
4682 break;
4683 case 'G':
4684 require_running_or_break (cs.own_buf);
4685 if (cs.current_traceframe >= 0)
4686 write_enn (cs.own_buf);
4687 else
4689 struct regcache *regcache;
4691 if (!set_desired_thread ())
4692 write_enn (cs.own_buf);
4693 else
4695 regcache = get_thread_regcache (current_thread, 1);
4696 registers_from_string (regcache, &cs.own_buf[1]);
4697 write_ok (cs.own_buf);
4700 break;
4701 case 'm':
4703 require_running_or_break (cs.own_buf);
4704 decode_m_packet (&cs.own_buf[1], &mem_addr, &len);
4705 int res = gdb_read_memory (mem_addr, mem_buf, len);
4706 if (res < 0)
4707 write_enn (cs.own_buf);
4708 else
4709 bin2hex (mem_buf, cs.own_buf, res);
4711 break;
4712 case 'M':
4713 require_running_or_break (cs.own_buf);
4714 decode_M_packet (&cs.own_buf[1], &mem_addr, &len, &mem_buf);
4715 if (gdb_write_memory (mem_addr, mem_buf, len) == 0)
4716 write_ok (cs.own_buf);
4717 else
4718 write_enn (cs.own_buf);
4719 break;
4720 case 'X':
4721 require_running_or_break (cs.own_buf);
4722 if (decode_X_packet (&cs.own_buf[1], packet_len - 1,
4723 &mem_addr, &len, &mem_buf) < 0
4724 || gdb_write_memory (mem_addr, mem_buf, len) != 0)
4725 write_enn (cs.own_buf);
4726 else
4727 write_ok (cs.own_buf);
4728 break;
4729 case 'C':
4730 require_running_or_break (cs.own_buf);
4731 hex2bin (cs.own_buf + 1, &sig, 1);
4732 if (gdb_signal_to_host_p ((enum gdb_signal) sig))
4733 signal = gdb_signal_to_host ((enum gdb_signal) sig);
4734 else
4735 signal = 0;
4736 myresume (cs.own_buf, 0, signal);
4737 break;
4738 case 'S':
4739 require_running_or_break (cs.own_buf);
4740 hex2bin (cs.own_buf + 1, &sig, 1);
4741 if (gdb_signal_to_host_p ((enum gdb_signal) sig))
4742 signal = gdb_signal_to_host ((enum gdb_signal) sig);
4743 else
4744 signal = 0;
4745 myresume (cs.own_buf, 1, signal);
4746 break;
4747 case 'c':
4748 require_running_or_break (cs.own_buf);
4749 signal = 0;
4750 myresume (cs.own_buf, 0, signal);
4751 break;
4752 case 's':
4753 require_running_or_break (cs.own_buf);
4754 signal = 0;
4755 myresume (cs.own_buf, 1, signal);
4756 break;
4757 case 'Z': /* insert_ ... */
4758 /* Fallthrough. */
4759 case 'z': /* remove_ ... */
4761 char *dataptr;
4762 ULONGEST addr;
4763 int kind;
4764 char type = cs.own_buf[1];
4765 int res;
4766 const int insert = ch == 'Z';
4767 const char *p = &cs.own_buf[3];
4769 p = unpack_varlen_hex (p, &addr);
4770 kind = strtol (p + 1, &dataptr, 16);
4772 if (insert)
4774 struct gdb_breakpoint *bp;
4776 bp = set_gdb_breakpoint (type, addr, kind, &res);
4777 if (bp != NULL)
4779 res = 0;
4781 /* GDB may have sent us a list of *point parameters to
4782 be evaluated on the target's side. Read such list
4783 here. If we already have a list of parameters, GDB
4784 is telling us to drop that list and use this one
4785 instead. */
4786 clear_breakpoint_conditions_and_commands (bp);
4787 const char *options = dataptr;
4788 process_point_options (bp, &options);
4791 else
4792 res = delete_gdb_breakpoint (type, addr, kind);
4794 if (res == 0)
4795 write_ok (cs.own_buf);
4796 else if (res == 1)
4797 /* Unsupported. */
4798 cs.own_buf[0] = '\0';
4799 else
4800 write_enn (cs.own_buf);
4801 break;
4803 case 'k':
4804 response_needed = false;
4805 if (!target_running ())
4806 /* The packet we received doesn't make sense - but we can't
4807 reply to it, either. */
4808 return 0;
4810 fprintf (stderr, "Killing all inferiors\n");
4812 for_each_process (kill_inferior_callback);
4814 /* When using the extended protocol, we wait with no program
4815 running. The traditional protocol will exit instead. */
4816 if (extended_protocol)
4818 cs.last_status.set_exited (GDB_SIGNAL_KILL);
4819 return 0;
4821 else
4822 exit (0);
4824 case 'T':
4826 require_running_or_break (cs.own_buf);
4828 ptid_t thread_id = read_ptid (&cs.own_buf[1], NULL);
4829 if (find_thread_ptid (thread_id) == NULL)
4831 write_enn (cs.own_buf);
4832 break;
4835 if (mythread_alive (thread_id))
4836 write_ok (cs.own_buf);
4837 else
4838 write_enn (cs.own_buf);
4840 break;
4841 case 'R':
4842 response_needed = false;
4844 /* Restarting the inferior is only supported in the extended
4845 protocol. */
4846 if (extended_protocol)
4848 if (target_running ())
4849 for_each_process (kill_inferior_callback);
4851 fprintf (stderr, "GDBserver restarting\n");
4853 /* Wait till we are at 1st instruction in prog. */
4854 if (program_path.get () != NULL)
4856 target_create_inferior (program_path.get (), program_args);
4858 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
4860 /* Stopped at the first instruction of the target
4861 process. */
4862 cs.general_thread = cs.last_ptid;
4864 else
4866 /* Something went wrong. */
4867 cs.general_thread = null_ptid;
4870 else
4872 cs.last_status.set_exited (GDB_SIGNAL_KILL);
4874 return 0;
4876 else
4878 /* It is a request we don't understand. Respond with an
4879 empty packet so that gdb knows that we don't support this
4880 request. */
4881 cs.own_buf[0] = '\0';
4882 break;
4884 case 'v':
4885 /* Extended (long) request. */
4886 handle_v_requests (cs.own_buf, packet_len, &new_packet_len);
4887 break;
4889 default:
4890 /* It is a request we don't understand. Respond with an empty
4891 packet so that gdb knows that we don't support this
4892 request. */
4893 cs.own_buf[0] = '\0';
4894 break;
4897 if (new_packet_len != -1)
4898 putpkt_binary (cs.own_buf, new_packet_len);
4899 else
4900 putpkt (cs.own_buf);
4902 response_needed = false;
4904 if (exit_requested)
4905 return -1;
4907 return 0;
4910 /* Event-loop callback for serial events. */
4912 void
4913 handle_serial_event (int err, gdb_client_data client_data)
4915 threads_debug_printf ("handling possible serial event");
4917 /* Really handle it. */
4918 if (process_serial_event () < 0)
4920 keep_processing_events = false;
4921 return;
4924 /* Be sure to not change the selected thread behind GDB's back.
4925 Important in the non-stop mode asynchronous protocol. */
4926 set_desired_thread ();
4929 /* Push a stop notification on the notification queue. */
4931 static void
4932 push_stop_notification (ptid_t ptid, const target_waitstatus &status)
4934 struct vstop_notif *vstop_notif = new struct vstop_notif;
4936 vstop_notif->status = status;
4937 vstop_notif->ptid = ptid;
4938 /* Push Stop notification. */
4939 notif_push (&notif_stop, vstop_notif);
4942 /* Event-loop callback for target events. */
4944 void
4945 handle_target_event (int err, gdb_client_data client_data)
4947 client_state &cs = get_client_state ();
4948 threads_debug_printf ("handling possible target event");
4950 cs.last_ptid = mywait (minus_one_ptid, &cs.last_status,
4951 TARGET_WNOHANG, 1);
4953 if (cs.last_status.kind () == TARGET_WAITKIND_NO_RESUMED)
4955 if (gdb_connected () && report_no_resumed)
4956 push_stop_notification (null_ptid, cs.last_status);
4958 else if (cs.last_status.kind () != TARGET_WAITKIND_IGNORE)
4960 int pid = cs.last_ptid.pid ();
4961 struct process_info *process = find_process_pid (pid);
4962 int forward_event = !gdb_connected () || process->gdb_detached;
4964 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
4965 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
4967 mark_breakpoints_out (process);
4968 target_mourn_inferior (cs.last_ptid);
4970 else if (cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED)
4972 else
4974 /* We're reporting this thread as stopped. Update its
4975 "want-stopped" state to what the client wants, until it
4976 gets a new resume action. */
4977 current_thread->last_resume_kind = resume_stop;
4978 current_thread->last_status = cs.last_status;
4981 if (forward_event)
4983 if (!target_running ())
4985 /* The last process exited. We're done. */
4986 exit (0);
4989 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
4990 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED
4991 || cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED)
4993 else
4995 /* A thread stopped with a signal, but gdb isn't
4996 connected to handle it. Pass it down to the
4997 inferior, as if it wasn't being traced. */
4998 enum gdb_signal signal;
5000 threads_debug_printf ("GDB not connected; forwarding event %d for"
5001 " [%s]",
5002 (int) cs.last_status.kind (),
5003 target_pid_to_str (cs.last_ptid).c_str ());
5005 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
5006 signal = cs.last_status.sig ();
5007 else
5008 signal = GDB_SIGNAL_0;
5009 target_continue (cs.last_ptid, signal);
5012 else
5014 push_stop_notification (cs.last_ptid, cs.last_status);
5016 if (cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED
5017 && !target_any_resumed ())
5019 target_waitstatus ws;
5020 ws.set_no_resumed ();
5021 push_stop_notification (null_ptid, ws);
5026 /* Be sure to not change the selected thread behind GDB's back.
5027 Important in the non-stop mode asynchronous protocol. */
5028 set_desired_thread ();
5031 /* See gdbsupport/event-loop.h. */
5034 invoke_async_signal_handlers ()
5036 return 0;
5039 /* See gdbsupport/event-loop.h. */
5042 check_async_event_handlers ()
5044 return 0;
5047 /* See gdbsupport/errors.h */
5049 void
5050 flush_streams ()
5052 fflush (stdout);
5053 fflush (stderr);
5056 /* See gdbsupport/gdb_select.h. */
5059 gdb_select (int n, fd_set *readfds, fd_set *writefds,
5060 fd_set *exceptfds, struct timeval *timeout)
5062 return select (n, readfds, writefds, exceptfds, timeout);
5065 #if GDB_SELF_TEST
5066 namespace selftests
5069 void
5070 reset ()
5073 } // namespace selftests
5074 #endif /* GDB_SELF_TEST */