Remove Debian from SECURITY.txt
[binutils-gdb.git] / gdbserver / server.cc
blobb7ea4ccfd03da32c00e31d248173507d4f8b68c4
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 if (strncmp (op, "pt:event-tracing=", strlen ("pt:event-tracing=")) == 0)
555 op += strlen ("pt:event-tracing=");
556 if (strncmp (op, "\"yes\"", strlen ("\"yes\"")) == 0)
557 current_btrace_conf.pt.event_tracing = true;
558 else if (strncmp (op, "\"no\"", strlen ("\"no\"")) == 0)
559 current_btrace_conf.pt.event_tracing = false;
560 else
562 strcpy (own_buf, "E.Bad event-tracing value.");
563 return -1;
566 else
568 strcpy (own_buf, "E.Bad Qbtrace configuration option.");
569 return -1;
572 write_ok (own_buf);
573 return 1;
576 /* Create the qMemTags packet reply given TAGS.
578 Returns true if parsing succeeded and false otherwise. */
580 static bool
581 create_fetch_memtags_reply (char *reply, const gdb::byte_vector &tags)
583 /* It is an error to pass a zero-sized tag vector. */
584 gdb_assert (tags.size () != 0);
586 std::string packet ("m");
588 /* Write the tag data. */
589 packet += bin2hex (tags.data (), tags.size ());
591 /* Check if the reply is too big for the packet to handle. */
592 if (PBUFSIZ < packet.size ())
593 return false;
595 strcpy (reply, packet.c_str ());
596 return true;
599 /* Parse the QMemTags request into ADDR, LEN and TAGS.
601 Returns true if parsing succeeded and false otherwise. */
603 static bool
604 parse_store_memtags_request (char *request, CORE_ADDR *addr, size_t *len,
605 gdb::byte_vector &tags, int *type)
607 gdb_assert (startswith (request, "QMemTags:"));
609 const char *p = request + strlen ("QMemTags:");
611 /* Read address and length. */
612 unsigned int length = 0;
613 p = decode_m_packet_params (p, addr, &length, ':');
614 *len = length;
616 /* Read the tag type. */
617 ULONGEST tag_type = 0;
618 p = unpack_varlen_hex (p, &tag_type);
619 *type = (int) tag_type;
621 /* Make sure there is a colon after the type. */
622 if (*p != ':')
623 return false;
625 /* Skip the colon. */
626 p++;
628 /* Read the tag data. */
629 tags = hex2bin (p);
631 return true;
634 /* Parse thread options starting at *P and return them. On exit,
635 advance *P past the options. */
637 static gdb_thread_options
638 parse_gdb_thread_options (const char **p)
640 ULONGEST options = 0;
641 *p = unpack_varlen_hex (*p, &options);
642 return (gdb_thread_option) options;
645 /* Handle all of the extended 'Q' packets. */
647 static void
648 handle_general_set (char *own_buf)
650 client_state &cs = get_client_state ();
651 if (startswith (own_buf, "QPassSignals:"))
653 int numsigs = (int) GDB_SIGNAL_LAST, i;
654 const char *p = own_buf + strlen ("QPassSignals:");
655 CORE_ADDR cursig;
657 p = decode_address_to_semicolon (&cursig, p);
658 for (i = 0; i < numsigs; i++)
660 if (i == cursig)
662 cs.pass_signals[i] = 1;
663 if (*p == '\0')
664 /* Keep looping, to clear the remaining signals. */
665 cursig = -1;
666 else
667 p = decode_address_to_semicolon (&cursig, p);
669 else
670 cs.pass_signals[i] = 0;
672 strcpy (own_buf, "OK");
673 return;
676 if (startswith (own_buf, "QProgramSignals:"))
678 int numsigs = (int) GDB_SIGNAL_LAST, i;
679 const char *p = own_buf + strlen ("QProgramSignals:");
680 CORE_ADDR cursig;
682 cs.program_signals_p = 1;
684 p = decode_address_to_semicolon (&cursig, p);
685 for (i = 0; i < numsigs; i++)
687 if (i == cursig)
689 cs.program_signals[i] = 1;
690 if (*p == '\0')
691 /* Keep looping, to clear the remaining signals. */
692 cursig = -1;
693 else
694 p = decode_address_to_semicolon (&cursig, p);
696 else
697 cs.program_signals[i] = 0;
699 strcpy (own_buf, "OK");
700 return;
703 if (startswith (own_buf, "QCatchSyscalls:"))
705 const char *p = own_buf + sizeof ("QCatchSyscalls:") - 1;
706 int enabled = -1;
707 CORE_ADDR sysno;
708 struct process_info *process;
710 if (!target_running () || !target_supports_catch_syscall ())
712 write_enn (own_buf);
713 return;
716 if (strcmp (p, "0") == 0)
717 enabled = 0;
718 else if (p[0] == '1' && (p[1] == ';' || p[1] == '\0'))
719 enabled = 1;
720 else
722 fprintf (stderr, "Unknown catch-syscalls mode requested: %s\n",
723 own_buf);
724 write_enn (own_buf);
725 return;
728 process = current_process ();
729 process->syscalls_to_catch.clear ();
731 if (enabled)
733 p += 1;
734 if (*p == ';')
736 p += 1;
737 while (*p != '\0')
739 p = decode_address_to_semicolon (&sysno, p);
740 process->syscalls_to_catch.push_back (sysno);
743 else
744 process->syscalls_to_catch.push_back (ANY_SYSCALL);
747 write_ok (own_buf);
748 return;
751 if (strcmp (own_buf, "QEnvironmentReset") == 0)
753 our_environ = gdb_environ::from_host_environ ();
755 write_ok (own_buf);
756 return;
759 if (startswith (own_buf, "QEnvironmentHexEncoded:"))
761 const char *p = own_buf + sizeof ("QEnvironmentHexEncoded:") - 1;
762 /* The final form of the environment variable. FINAL_VAR will
763 hold the 'VAR=VALUE' format. */
764 std::string final_var = hex2str (p);
765 std::string var_name, var_value;
767 remote_debug_printf ("[QEnvironmentHexEncoded received '%s']", p);
768 remote_debug_printf ("[Environment variable to be set: '%s']",
769 final_var.c_str ());
771 size_t pos = final_var.find ('=');
772 if (pos == std::string::npos)
774 warning (_("Unexpected format for environment variable: '%s'"),
775 final_var.c_str ());
776 write_enn (own_buf);
777 return;
780 var_name = final_var.substr (0, pos);
781 var_value = final_var.substr (pos + 1, std::string::npos);
783 our_environ.set (var_name.c_str (), var_value.c_str ());
785 write_ok (own_buf);
786 return;
789 if (startswith (own_buf, "QEnvironmentUnset:"))
791 const char *p = own_buf + sizeof ("QEnvironmentUnset:") - 1;
792 std::string varname = hex2str (p);
794 remote_debug_printf ("[QEnvironmentUnset received '%s']", p);
795 remote_debug_printf ("[Environment variable to be unset: '%s']",
796 varname.c_str ());
798 our_environ.unset (varname.c_str ());
800 write_ok (own_buf);
801 return;
804 if (strcmp (own_buf, "QStartNoAckMode") == 0)
806 remote_debug_printf ("[noack mode enabled]");
808 cs.noack_mode = 1;
809 write_ok (own_buf);
810 return;
813 if (startswith (own_buf, "QNonStop:"))
815 char *mode = own_buf + 9;
816 int req = -1;
817 const char *req_str;
819 if (strcmp (mode, "0") == 0)
820 req = 0;
821 else if (strcmp (mode, "1") == 0)
822 req = 1;
823 else
825 /* We don't know what this mode is, so complain to
826 GDB. */
827 fprintf (stderr, "Unknown non-stop mode requested: %s\n",
828 own_buf);
829 write_enn (own_buf);
830 return;
833 req_str = req ? "non-stop" : "all-stop";
834 if (the_target->start_non_stop (req == 1) != 0)
836 fprintf (stderr, "Setting %s mode failed\n", req_str);
837 write_enn (own_buf);
838 return;
841 non_stop = (req != 0);
843 remote_debug_printf ("[%s mode enabled]", req_str);
845 write_ok (own_buf);
846 return;
849 if (startswith (own_buf, "QDisableRandomization:"))
851 char *packet = own_buf + strlen ("QDisableRandomization:");
852 ULONGEST setting;
854 unpack_varlen_hex (packet, &setting);
855 cs.disable_randomization = setting;
857 remote_debug_printf (cs.disable_randomization
858 ? "[address space randomization disabled]"
859 : "[address space randomization enabled]");
861 write_ok (own_buf);
862 return;
865 if (target_supports_tracepoints ()
866 && handle_tracepoint_general_set (own_buf))
867 return;
869 if (startswith (own_buf, "QAgent:"))
871 char *mode = own_buf + strlen ("QAgent:");
872 int req = 0;
874 if (strcmp (mode, "0") == 0)
875 req = 0;
876 else if (strcmp (mode, "1") == 0)
877 req = 1;
878 else
880 /* We don't know what this value is, so complain to GDB. */
881 sprintf (own_buf, "E.Unknown QAgent value");
882 return;
885 /* Update the flag. */
886 use_agent = req;
887 remote_debug_printf ("[%s agent]", req ? "Enable" : "Disable");
888 write_ok (own_buf);
889 return;
892 if (handle_btrace_general_set (own_buf))
893 return;
895 if (handle_btrace_conf_general_set (own_buf))
896 return;
898 if (startswith (own_buf, "QThreadEvents:"))
900 char *mode = own_buf + strlen ("QThreadEvents:");
901 enum tribool req = TRIBOOL_UNKNOWN;
903 if (strcmp (mode, "0") == 0)
904 req = TRIBOOL_FALSE;
905 else if (strcmp (mode, "1") == 0)
906 req = TRIBOOL_TRUE;
907 else
909 /* We don't know what this mode is, so complain to GDB. */
910 std::string err
911 = string_printf ("E.Unknown thread-events mode requested: %s\n",
912 mode);
913 strcpy (own_buf, err.c_str ());
914 return;
917 cs.report_thread_events = (req == TRIBOOL_TRUE);
919 remote_debug_printf ("[thread events are now %s]\n",
920 cs.report_thread_events ? "enabled" : "disabled");
922 write_ok (own_buf);
923 return;
926 if (startswith (own_buf, "QThreadOptions;"))
928 const char *p = own_buf + strlen ("QThreadOptions");
930 gdb_thread_options supported_options = target_supported_thread_options ();
931 if (supported_options == 0)
933 /* Something went wrong -- we don't support any option, but
934 GDB sent the packet anyway. */
935 write_enn (own_buf);
936 return;
939 /* We could store the options directly in thread->thread_options
940 without this map, but that would mean that a QThreadOptions
941 packet with a wildcard like "QThreadOptions;0;3:TID" would
942 result in the debug logs showing:
944 [options for TID are now 0x0]
945 [options for TID are now 0x3]
947 It's nicer if we only print the final options for each TID,
948 and if we only print about it if the options changed compared
949 to the options that were previously set on the thread. */
950 std::unordered_map<thread_info *, gdb_thread_options> set_options;
952 while (*p != '\0')
954 if (p[0] != ';')
956 write_enn (own_buf);
957 return;
959 p++;
961 /* Read the options. */
963 gdb_thread_options options = parse_gdb_thread_options (&p);
965 if ((options & ~supported_options) != 0)
967 /* GDB asked for an unknown or unsupported option, so
968 error out. */
969 std::string err
970 = string_printf ("E.Unknown thread options requested: %s\n",
971 to_string (options).c_str ());
972 strcpy (own_buf, err.c_str ());
973 return;
976 ptid_t ptid;
978 if (p[0] == ';' || p[0] == '\0')
979 ptid = minus_one_ptid;
980 else if (p[0] == ':')
982 const char *q;
984 ptid = read_ptid (p + 1, &q);
986 if (p == q)
988 write_enn (own_buf);
989 return;
991 p = q;
992 if (p[0] != ';' && p[0] != '\0')
994 write_enn (own_buf);
995 return;
998 else
1000 write_enn (own_buf);
1001 return;
1004 /* Convert PID.-1 => PID.0 for ptid.matches. */
1005 if (ptid.lwp () == -1)
1006 ptid = ptid_t (ptid.pid ());
1008 for_each_thread ([&] (thread_info *thread)
1010 if (thread->id.matches (ptid))
1011 set_options[thread] = options;
1015 for (const auto &iter : set_options)
1017 thread_info *thread = iter.first;
1018 gdb_thread_options options = iter.second;
1020 if (thread->thread_options != options)
1022 threads_debug_printf ("[options for %s are now %s]\n",
1023 target_pid_to_str (thread->id).c_str (),
1024 to_string (options).c_str ());
1026 thread->thread_options = options;
1030 write_ok (own_buf);
1031 return;
1034 if (startswith (own_buf, "QStartupWithShell:"))
1036 const char *value = own_buf + strlen ("QStartupWithShell:");
1038 if (strcmp (value, "1") == 0)
1039 startup_with_shell = true;
1040 else if (strcmp (value, "0") == 0)
1041 startup_with_shell = false;
1042 else
1044 /* Unknown value. */
1045 fprintf (stderr, "Unknown value to startup-with-shell: %s\n",
1046 own_buf);
1047 write_enn (own_buf);
1048 return;
1051 remote_debug_printf ("[Inferior will %s started with shell]",
1052 startup_with_shell ? "be" : "not be");
1054 write_ok (own_buf);
1055 return;
1058 if (startswith (own_buf, "QSetWorkingDir:"))
1060 const char *p = own_buf + strlen ("QSetWorkingDir:");
1062 if (*p != '\0')
1064 std::string path = hex2str (p);
1066 remote_debug_printf ("[Set the inferior's current directory to %s]",
1067 path.c_str ());
1069 set_inferior_cwd (std::move (path));
1071 else
1073 /* An empty argument means that we should clear out any
1074 previously set cwd for the inferior. */
1075 set_inferior_cwd ("");
1077 remote_debug_printf ("[Unset the inferior's current directory; will "
1078 "use gdbserver's cwd]");
1080 write_ok (own_buf);
1082 return;
1086 /* Handle store memory tags packets. */
1087 if (startswith (own_buf, "QMemTags:")
1088 && target_supports_memory_tagging ())
1090 gdb::byte_vector tags;
1091 CORE_ADDR addr = 0;
1092 size_t len = 0;
1093 int type = 0;
1095 require_running_or_return (own_buf);
1097 bool ret = parse_store_memtags_request (own_buf, &addr, &len, tags,
1098 &type);
1100 if (ret)
1101 ret = the_target->store_memtags (addr, len, tags, type);
1103 if (!ret)
1104 write_enn (own_buf);
1105 else
1106 write_ok (own_buf);
1108 return;
1111 /* Otherwise we didn't know what packet it was. Say we didn't
1112 understand it. */
1113 own_buf[0] = 0;
1116 static const char *
1117 get_features_xml (const char *annex)
1119 const struct target_desc *desc = current_target_desc ();
1121 /* `desc->xmltarget' defines what to return when looking for the
1122 "target.xml" file. Its contents can either be verbatim XML code
1123 (prefixed with a '@') or else the name of the actual XML file to
1124 be used in place of "target.xml".
1126 This variable is set up from the auto-generated
1127 init_registers_... routine for the current target. */
1129 if (strcmp (annex, "target.xml") == 0)
1131 const char *ret = tdesc_get_features_xml (desc);
1133 if (*ret == '@')
1134 return ret + 1;
1135 else
1136 annex = ret;
1139 #ifdef USE_XML
1141 int i;
1143 /* Look for the annex. */
1144 for (i = 0; xml_builtin[i][0] != NULL; i++)
1145 if (strcmp (annex, xml_builtin[i][0]) == 0)
1146 break;
1148 if (xml_builtin[i][0] != NULL)
1149 return xml_builtin[i][1];
1151 #endif
1153 return NULL;
1156 static void
1157 monitor_show_help (void)
1159 monitor_output ("The following monitor commands are supported:\n");
1160 monitor_output (" set debug on\n");
1161 monitor_output (" Enable general debugging messages\n");
1162 monitor_output (" set debug off\n");
1163 monitor_output (" Disable all debugging messages\n");
1164 monitor_output (" set debug COMPONENT <off|on>\n");
1165 monitor_output (" Enable debugging messages for COMPONENT, which is\n");
1166 monitor_output (" one of: all, threads, remote, event-loop.\n");
1167 monitor_output (" set debug-hw-points <0|1>\n");
1168 monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
1169 monitor_output (" set debug-format option1[,option2,...]\n");
1170 monitor_output (" Add additional information to debugging messages\n");
1171 monitor_output (" Options: all, none, timestamp\n");
1172 monitor_output (" exit\n");
1173 monitor_output (" Quit GDBserver\n");
1176 /* Read trace frame or inferior memory. Returns the number of bytes
1177 actually read, zero when no further transfer is possible, and -1 on
1178 error. Return of a positive value smaller than LEN does not
1179 indicate there's no more to be read, only the end of the transfer.
1180 E.g., when GDB reads memory from a traceframe, a first request may
1181 be served from a memory block that does not cover the whole request
1182 length. A following request gets the rest served from either
1183 another block (of the same traceframe) or from the read-only
1184 regions. */
1186 static int
1187 gdb_read_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
1189 client_state &cs = get_client_state ();
1190 int res;
1192 if (cs.current_traceframe >= 0)
1194 ULONGEST nbytes;
1195 ULONGEST length = len;
1197 if (traceframe_read_mem (cs.current_traceframe,
1198 memaddr, myaddr, len, &nbytes))
1199 return -1;
1200 /* Data read from trace buffer, we're done. */
1201 if (nbytes > 0)
1202 return nbytes;
1203 if (!in_readonly_region (memaddr, length))
1204 return -1;
1205 /* Otherwise we have a valid readonly case, fall through. */
1206 /* (assume no half-trace half-real blocks for now) */
1209 if (set_desired_process ())
1210 res = read_inferior_memory (memaddr, myaddr, len);
1211 else
1212 res = 1;
1214 return res == 0 ? len : -1;
1217 /* Write trace frame or inferior memory. Actually, writing to trace
1218 frames is forbidden. */
1220 static int
1221 gdb_write_memory (CORE_ADDR memaddr, const unsigned char *myaddr, int len)
1223 client_state &cs = get_client_state ();
1224 if (cs.current_traceframe >= 0)
1225 return EIO;
1226 else
1228 int ret;
1230 if (set_desired_process ())
1231 ret = target_write_memory (memaddr, myaddr, len);
1232 else
1233 ret = EIO;
1234 return ret;
1238 /* Handle qSearch:memory packets. */
1240 static void
1241 handle_search_memory (char *own_buf, int packet_len)
1243 CORE_ADDR start_addr;
1244 CORE_ADDR search_space_len;
1245 gdb_byte *pattern;
1246 unsigned int pattern_len;
1247 int found;
1248 CORE_ADDR found_addr;
1249 int cmd_name_len = sizeof ("qSearch:memory:") - 1;
1251 pattern = (gdb_byte *) malloc (packet_len);
1252 if (pattern == NULL)
1253 error ("Unable to allocate memory to perform the search");
1255 if (decode_search_memory_packet (own_buf + cmd_name_len,
1256 packet_len - cmd_name_len,
1257 &start_addr, &search_space_len,
1258 pattern, &pattern_len) < 0)
1260 free (pattern);
1261 error ("Error in parsing qSearch:memory packet");
1264 auto read_memory = [] (CORE_ADDR addr, gdb_byte *result, size_t len)
1266 return gdb_read_memory (addr, result, len) == len;
1269 found = simple_search_memory (read_memory, start_addr, search_space_len,
1270 pattern, pattern_len, &found_addr);
1272 if (found > 0)
1273 sprintf (own_buf, "1,%lx", (long) found_addr);
1274 else if (found == 0)
1275 strcpy (own_buf, "0");
1276 else
1277 strcpy (own_buf, "E00");
1279 free (pattern);
1282 /* Handle the "D" packet. */
1284 static void
1285 handle_detach (char *own_buf)
1287 client_state &cs = get_client_state ();
1289 process_info *process;
1291 if (cs.multi_process)
1293 /* skip 'D;' */
1294 int pid = strtol (&own_buf[2], NULL, 16);
1296 process = find_process_pid (pid);
1298 else
1299 process = current_process ();
1301 if (process == NULL)
1303 write_enn (own_buf);
1304 return;
1307 if ((tracing && disconnected_tracing) || any_persistent_commands (process))
1309 if (tracing && disconnected_tracing)
1310 fprintf (stderr,
1311 "Disconnected tracing in effect, "
1312 "leaving gdbserver attached to the process\n");
1314 if (any_persistent_commands (process))
1315 fprintf (stderr,
1316 "Persistent commands are present, "
1317 "leaving gdbserver attached to the process\n");
1319 /* Make sure we're in non-stop/async mode, so we we can both
1320 wait for an async socket accept, and handle async target
1321 events simultaneously. There's also no point either in
1322 having the target stop all threads, when we're going to
1323 pass signals down without informing GDB. */
1324 if (!non_stop)
1326 threads_debug_printf ("Forcing non-stop mode");
1328 non_stop = true;
1329 the_target->start_non_stop (true);
1332 process->gdb_detached = 1;
1334 /* Detaching implicitly resumes all threads. */
1335 target_continue_no_signal (minus_one_ptid);
1337 write_ok (own_buf);
1338 return;
1341 fprintf (stderr, "Detaching from process %d\n", process->pid);
1342 stop_tracing ();
1344 /* We'll need this after PROCESS has been destroyed. */
1345 int pid = process->pid;
1347 /* If this process has an unreported fork child, that child is not known to
1348 GDB, so GDB won't take care of detaching it. We must do it here.
1350 Here, we specifically don't want to use "safe iteration", as detaching
1351 another process might delete the next thread in the iteration, which is
1352 the one saved by the safe iterator. We will never delete the currently
1353 iterated on thread, so standard iteration should be safe. */
1354 for (thread_info &thread : process->thread_list ())
1356 /* Only threads that have a pending fork event. */
1357 target_waitkind kind;
1358 thread_info *child = target_thread_pending_child (&thread, &kind);
1359 if (child == nullptr || kind == TARGET_WAITKIND_THREAD_CLONED)
1360 continue;
1362 process_info *fork_child_process = child->process ();
1363 int fork_child_pid = fork_child_process->pid;
1365 if (detach_inferior (fork_child_process) != 0)
1366 warning (_("Failed to detach fork child %s, child of %s"),
1367 target_pid_to_str (ptid_t (fork_child_pid)).c_str (),
1368 target_pid_to_str (thread.id).c_str ());
1371 if (detach_inferior (process) != 0)
1372 write_enn (own_buf);
1373 else
1375 discard_queued_stop_replies (ptid_t (pid));
1376 write_ok (own_buf);
1378 if (extended_protocol || target_running ())
1380 /* There is still at least one inferior remaining or
1381 we are in extended mode, so don't terminate gdbserver,
1382 and instead treat this like a normal program exit. */
1383 cs.last_status.set_exited (0);
1384 cs.last_ptid = ptid_t (pid);
1386 switch_to_thread (nullptr);
1388 else
1390 putpkt (own_buf);
1391 remote_close ();
1393 /* If we are attached, then we can exit. Otherwise, we
1394 need to hang around doing nothing, until the child is
1395 gone. */
1396 join_inferior (pid);
1397 exit (0);
1402 /* Parse options to --debug-format= and "monitor set debug-format".
1403 ARG is the text after "--debug-format=" or "monitor set debug-format".
1404 IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
1405 This triggers calls to monitor_output.
1406 The result is an empty string if all options were parsed ok, otherwise an
1407 error message which the caller must free.
1409 N.B. These commands affect all debug format settings, they are not
1410 cumulative. If a format is not specified, it is turned off.
1411 However, we don't go to extra trouble with things like
1412 "monitor set debug-format all,none,timestamp".
1413 Instead we just parse them one at a time, in order.
1415 The syntax for "monitor set debug" we support here is not identical
1416 to gdb's "set debug foo on|off" because we also use this function to
1417 parse "--debug-format=foo,bar". */
1419 static std::string
1420 parse_debug_format_options (const char *arg, int is_monitor)
1422 /* First turn all debug format options off. */
1423 debug_timestamp = 0;
1425 /* First remove leading spaces, for "monitor set debug-format". */
1426 while (isspace (*arg))
1427 ++arg;
1429 std::vector<gdb::unique_xmalloc_ptr<char>> options
1430 = delim_string_to_char_ptr_vec (arg, ',');
1432 for (const gdb::unique_xmalloc_ptr<char> &option : options)
1434 if (strcmp (option.get (), "all") == 0)
1436 debug_timestamp = 1;
1437 if (is_monitor)
1438 monitor_output ("All extra debug format options enabled.\n");
1440 else if (strcmp (option.get (), "none") == 0)
1442 debug_timestamp = 0;
1443 if (is_monitor)
1444 monitor_output ("All extra debug format options disabled.\n");
1446 else if (strcmp (option.get (), "timestamp") == 0)
1448 debug_timestamp = 1;
1449 if (is_monitor)
1450 monitor_output ("Timestamps will be added to debug output.\n");
1452 else if (*option == '\0')
1454 /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
1455 continue;
1457 else
1458 return string_printf ("Unknown debug-format argument: \"%s\"\n",
1459 option.get ());
1462 return std::string ();
1465 /* A wrapper to enable, or disable a debug flag. These are debug flags
1466 that control the debug output from gdbserver, that developers might
1467 want, this is not something most end users will need. */
1469 struct debug_opt
1471 /* NAME is the name of this debug option, this should be a simple string
1472 containing no whitespace, starting with a letter from isalpha(), and
1473 contain only isalnum() characters and '_' underscore and '-' hyphen.
1475 SETTER is a callback function used to set the debug variable. This
1476 callback will be passed true to enable the debug setting, or false to
1477 disable the debug setting. */
1478 debug_opt (const char *name, std::function<void (bool)> setter)
1479 : m_name (name),
1480 m_setter (setter)
1482 gdb_assert (isalpha (*name));
1485 /* Called to enable or disable the debug setting. */
1486 void set (bool enable) const
1488 m_setter (enable);
1491 /* Return the name of this debug option. */
1492 const char *name () const
1493 { return m_name; }
1495 private:
1496 /* The name of this debug option. */
1497 const char *m_name;
1499 /* The callback to update the debug setting. */
1500 std::function<void (bool)> m_setter;
1503 /* The set of all debug options that gdbserver supports. These are the
1504 options that can be passed to the command line '--debug=...' flag, or to
1505 the monitor command 'monitor set debug ...'. */
1507 static std::vector<debug_opt> all_debug_opt {
1508 {"threads", [] (bool enable)
1510 debug_threads = enable;
1512 {"remote", [] (bool enable)
1514 remote_debug = enable;
1516 {"event-loop", [] (bool enable)
1518 debug_event_loop = (enable ? debug_event_loop_kind::ALL
1519 : debug_event_loop_kind::OFF);
1523 /* Parse the options to --debug=...
1525 OPTIONS is the string of debug components which should be enabled (or
1526 disabled), and must not be nullptr. An empty OPTIONS string is valid,
1527 in which case a default set of debug components will be enabled.
1529 An unknown, or otherwise invalid debug component will result in an
1530 exception being thrown.
1532 OPTIONS can consist of multiple debug component names separated by a
1533 comma. Debugging for each component will be turned on. The special
1534 component 'all' can be used to enable debugging for all components.
1536 A component can also be prefixed with '-' to disable debugging of that
1537 component, so a user might use: '--debug=all,-remote', to enable all
1538 debugging, except for the remote (protocol) component. Components are
1539 processed left to write in the OPTIONS list. */
1541 static void
1542 parse_debug_options (const char *options)
1544 gdb_assert (options != nullptr);
1546 /* Empty options means the "default" set. This exists mostly for
1547 backwards compatibility with gdbserver's legacy behaviour. */
1548 if (*options == '\0')
1549 options = "+threads";
1551 while (*options != '\0')
1553 const char *end = strchrnul (options, ',');
1555 bool enable = *options != '-';
1556 if (*options == '-' || *options == '+')
1557 ++options;
1559 std::string opt (options, end - options);
1561 if (opt.size () == 0)
1562 error ("invalid empty debug option");
1564 bool is_opt_all = opt == "all";
1566 bool found = false;
1567 for (const auto &debug_opt : all_debug_opt)
1568 if (is_opt_all || opt == debug_opt.name ())
1570 debug_opt.set (enable);
1571 found = true;
1572 if (!is_opt_all)
1573 break;
1576 if (!found)
1577 error ("unknown debug option '%s'", opt.c_str ());
1579 options = (*end == ',') ? end + 1 : end;
1583 /* Called from the 'monitor' command handler, to handle general 'set debug'
1584 monitor commands with one of the formats:
1586 set debug COMPONENT VALUE
1587 set debug VALUE
1589 In both of these command formats VALUE can be 'on', 'off', '1', or '0'
1590 with 1/0 being equivalent to on/off respectively.
1592 In the no-COMPONENT version of the command, if VALUE is 'on' (or '1')
1593 then the component 'threads' is assumed, this is for backward
1594 compatibility, but maybe in the future we might find a better "default"
1595 set of debug flags to enable.
1597 In the no-COMPONENT version of the command, if VALUE is 'off' (or '0')
1598 then all debugging is turned off.
1600 Otherwise, COMPONENT must be one of the known debug components, and that
1601 component is either enabled or disabled as appropriate.
1603 The string MON contains either 'COMPONENT VALUE' or just the 'VALUE' for
1604 the second command format, the 'set debug ' has been stripped off
1605 already.
1607 Return a string containing an error message if something goes wrong,
1608 this error can be returned as part of the monitor command output. If
1609 everything goes correctly then the debug global will have been updated,
1610 and an empty string is returned. */
1612 static std::string
1613 handle_general_monitor_debug (const char *mon)
1615 mon = skip_spaces (mon);
1617 if (*mon == '\0')
1618 return "No debug component name found.\n";
1620 /* Find the first word within MON. This is either the component name,
1621 or the value if no component has been given. */
1622 const char *end = skip_to_space (mon);
1623 std::string component (mon, end - mon);
1624 if (component.find (',') != component.npos || component[0] == '-'
1625 || component[0] == '+')
1626 return "Invalid character found in debug component name.\n";
1628 /* In ACTION_STR we create a string that will be passed to the
1629 parse_debug_options string. This will be either '+COMPONENT' or
1630 '-COMPONENT' depending on whether we want to enable or disable
1631 COMPONENT. */
1632 std::string action_str;
1634 /* If parse_debug_options succeeds, then MSG will be returned to the user
1635 as the output of the monitor command. */
1636 std::string msg;
1638 /* Check for 'set debug off', this disables all debug output. */
1639 if (component == "0" || component == "off")
1641 if (*skip_spaces (end) != '\0')
1642 return string_printf
1643 ("Junk '%s' found at end of 'set debug %s' command.\n",
1644 skip_spaces (end), std::string (mon, end - mon).c_str ());
1646 action_str = "-all";
1647 msg = "All debug output disabled.\n";
1649 /* Check for 'set debug on', this disables a general set of debug. */
1650 else if (component == "1" || component == "on")
1652 if (*skip_spaces (end) != '\0')
1653 return string_printf
1654 ("Junk '%s' found at end of 'set debug %s' command.\n",
1655 skip_spaces (end), std::string (mon, end - mon).c_str ());
1657 action_str = "+threads";
1658 msg = "General debug output enabled.\n";
1660 /* Otherwise we should have 'set debug COMPONENT VALUE'. Extract the two
1661 parts and validate. */
1662 else
1664 /* Figure out the value the user passed. */
1665 const char *value_start = skip_spaces (end);
1666 if (*value_start == '\0')
1667 return string_printf ("Missing value for 'set debug %s' command.\n",
1668 mon);
1670 const char *after_value = skip_to_space (value_start);
1671 if (*skip_spaces (after_value) != '\0')
1672 return string_printf
1673 ("Junk '%s' found at end of 'set debug %s' command.\n",
1674 skip_spaces (after_value),
1675 std::string (mon, after_value - mon).c_str ());
1677 std::string value (value_start, after_value - value_start);
1679 /* Check VALUE to see if we are enabling, or disabling. */
1680 bool enable;
1681 if (value == "0" || value == "off")
1682 enable = false;
1683 else if (value == "1" || value == "on")
1684 enable = true;
1685 else
1686 return string_printf ("Invalid value '%s' for 'set debug %s'.\n",
1687 value.c_str (),
1688 std::string (mon, end - mon).c_str ());
1690 action_str = std::string (enable ? "+" : "-") + component;
1691 msg = string_printf ("Debug output for '%s' %s.\n", component.c_str (),
1692 enable ? "enabled" : "disabled");
1695 gdb_assert (!msg.empty ());
1696 gdb_assert (!action_str.empty ());
1700 parse_debug_options (action_str.c_str ());
1701 monitor_output (msg.c_str ());
1703 catch (const gdb_exception_error &exception)
1705 return string_printf ("Error: %s\n", exception.what ());
1708 return {};
1711 /* Handle monitor commands not handled by target-specific handlers. */
1713 static void
1714 handle_monitor_command (char *mon, char *own_buf)
1716 if (startswith (mon, "set debug "))
1718 std::string error_msg
1719 = handle_general_monitor_debug (mon + sizeof ("set debug ") - 1);
1721 if (!error_msg.empty ())
1723 monitor_output (error_msg.c_str ());
1724 monitor_show_help ();
1725 write_enn (own_buf);
1728 else if (strcmp (mon, "set debug-hw-points 1") == 0)
1730 show_debug_regs = 1;
1731 monitor_output ("H/W point debugging output enabled.\n");
1733 else if (strcmp (mon, "set debug-hw-points 0") == 0)
1735 show_debug_regs = 0;
1736 monitor_output ("H/W point debugging output disabled.\n");
1738 else if (startswith (mon, "set debug-format "))
1740 std::string error_msg
1741 = parse_debug_format_options (mon + sizeof ("set debug-format ") - 1,
1744 if (!error_msg.empty ())
1746 monitor_output (error_msg.c_str ());
1747 monitor_show_help ();
1748 write_enn (own_buf);
1751 else if (strcmp (mon, "set debug-file") == 0)
1752 debug_set_output (nullptr);
1753 else if (startswith (mon, "set debug-file "))
1754 debug_set_output (mon + sizeof ("set debug-file ") - 1);
1755 else if (strcmp (mon, "help") == 0)
1756 monitor_show_help ();
1757 else if (strcmp (mon, "exit") == 0)
1758 exit_requested = true;
1759 else
1761 monitor_output ("Unknown monitor command.\n\n");
1762 monitor_show_help ();
1763 write_enn (own_buf);
1767 /* Associates a callback with each supported qXfer'able object. */
1769 struct qxfer
1771 /* The object this handler handles. */
1772 const char *object;
1774 /* Request that the target transfer up to LEN 8-bit bytes of the
1775 target's OBJECT. The OFFSET, for a seekable object, specifies
1776 the starting point. The ANNEX can be used to provide additional
1777 data-specific information to the target.
1779 Return the number of bytes actually transferred, zero when no
1780 further transfer is possible, -1 on error, -2 when the transfer
1781 is not supported, and -3 on a verbose error message that should
1782 be preserved. Return of a positive value smaller than LEN does
1783 not indicate the end of the object, only the end of the transfer.
1785 One, and only one, of readbuf or writebuf must be non-NULL. */
1786 int (*xfer) (const char *annex,
1787 gdb_byte *readbuf, const gdb_byte *writebuf,
1788 ULONGEST offset, LONGEST len);
1791 /* Handle qXfer:auxv:read. */
1793 static int
1794 handle_qxfer_auxv (const char *annex,
1795 gdb_byte *readbuf, const gdb_byte *writebuf,
1796 ULONGEST offset, LONGEST len)
1798 if (!the_target->supports_read_auxv () || writebuf != NULL)
1799 return -2;
1801 if (annex[0] != '\0' || current_thread == NULL)
1802 return -1;
1804 return the_target->read_auxv (current_thread->id.pid (), offset, readbuf,
1805 len);
1808 /* Handle qXfer:exec-file:read. */
1810 static int
1811 handle_qxfer_exec_file (const char *annex,
1812 gdb_byte *readbuf, const gdb_byte *writebuf,
1813 ULONGEST offset, LONGEST len)
1815 ULONGEST pid;
1816 int total_len;
1818 if (!the_target->supports_pid_to_exec_file () || writebuf != NULL)
1819 return -2;
1821 if (annex[0] == '\0')
1823 if (current_thread == NULL)
1824 return -1;
1826 pid = current_thread->id.pid ();
1828 else
1830 annex = unpack_varlen_hex (annex, &pid);
1831 if (annex[0] != '\0')
1832 return -1;
1835 if (pid <= 0)
1836 return -1;
1838 const char *file = the_target->pid_to_exec_file (pid);
1839 if (file == NULL)
1840 return -1;
1842 total_len = strlen (file);
1844 if (offset > total_len)
1845 return -1;
1847 if (offset + len > total_len)
1848 len = total_len - offset;
1850 memcpy (readbuf, file + offset, len);
1851 return len;
1854 /* Handle qXfer:features:read. */
1856 static int
1857 handle_qxfer_features (const char *annex,
1858 gdb_byte *readbuf, const gdb_byte *writebuf,
1859 ULONGEST offset, LONGEST len)
1861 const char *document;
1862 size_t total_len;
1864 if (writebuf != NULL)
1865 return -2;
1867 if (!target_running ())
1868 return -1;
1870 /* Grab the correct annex. */
1871 document = get_features_xml (annex);
1872 if (document == NULL)
1873 return -1;
1875 total_len = strlen (document);
1877 if (offset > total_len)
1878 return -1;
1880 if (offset + len > total_len)
1881 len = total_len - offset;
1883 memcpy (readbuf, document + offset, len);
1884 return len;
1887 /* Handle qXfer:libraries:read. */
1889 static int
1890 handle_qxfer_libraries (const char *annex,
1891 gdb_byte *readbuf, const gdb_byte *writebuf,
1892 ULONGEST offset, LONGEST len)
1894 if (writebuf != NULL)
1895 return -2;
1897 if (annex[0] != '\0' || current_thread == NULL)
1898 return -1;
1900 std::string document = "<library-list version=\"1.0\">\n";
1902 process_info *proc = current_process ();
1903 for (const dll_info &dll : proc->all_dlls)
1904 document += string_printf
1905 (" <library name=\"%s\"><segment address=\"0x%s\"/></library>\n",
1906 dll.name.c_str (), paddress (dll.base_addr));
1908 document += "</library-list>\n";
1910 if (offset > document.length ())
1911 return -1;
1913 if (offset + len > document.length ())
1914 len = document.length () - offset;
1916 memcpy (readbuf, &document[offset], len);
1918 return len;
1921 /* Handle qXfer:libraries-svr4:read. */
1923 static int
1924 handle_qxfer_libraries_svr4 (const char *annex,
1925 gdb_byte *readbuf, const gdb_byte *writebuf,
1926 ULONGEST offset, LONGEST len)
1928 if (writebuf != NULL)
1929 return -2;
1931 if (current_thread == NULL
1932 || !the_target->supports_qxfer_libraries_svr4 ())
1933 return -1;
1935 return the_target->qxfer_libraries_svr4 (annex, readbuf, writebuf,
1936 offset, len);
1939 /* Handle qXfer:osadata:read. */
1941 static int
1942 handle_qxfer_osdata (const char *annex,
1943 gdb_byte *readbuf, const gdb_byte *writebuf,
1944 ULONGEST offset, LONGEST len)
1946 if (!the_target->supports_qxfer_osdata () || writebuf != NULL)
1947 return -2;
1949 return the_target->qxfer_osdata (annex, readbuf, NULL, offset, len);
1952 /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
1954 static int
1955 handle_qxfer_siginfo (const char *annex,
1956 gdb_byte *readbuf, const gdb_byte *writebuf,
1957 ULONGEST offset, LONGEST len)
1959 if (!the_target->supports_qxfer_siginfo ())
1960 return -2;
1962 if (annex[0] != '\0' || current_thread == NULL)
1963 return -1;
1965 return the_target->qxfer_siginfo (annex, readbuf, writebuf, offset, len);
1968 /* Handle qXfer:statictrace:read. */
1970 static int
1971 handle_qxfer_statictrace (const char *annex,
1972 gdb_byte *readbuf, const gdb_byte *writebuf,
1973 ULONGEST offset, LONGEST len)
1975 client_state &cs = get_client_state ();
1976 ULONGEST nbytes;
1978 if (writebuf != NULL)
1979 return -2;
1981 if (annex[0] != '\0' || current_thread == NULL
1982 || cs.current_traceframe == -1)
1983 return -1;
1985 if (traceframe_read_sdata (cs.current_traceframe, offset,
1986 readbuf, len, &nbytes))
1987 return -1;
1988 return nbytes;
1991 /* Helper for handle_qxfer_threads_proper.
1992 Emit the XML to describe the thread of INF. */
1994 static void
1995 handle_qxfer_threads_worker (thread_info *thread, std::string *buffer)
1997 ptid_t ptid = thread->id;
1998 char ptid_s[100];
1999 int core = target_core_of_thread (ptid);
2000 char core_s[21];
2001 const char *name = target_thread_name (ptid);
2002 int handle_len;
2003 gdb_byte *handle;
2004 bool handle_status = target_thread_handle (ptid, &handle, &handle_len);
2006 /* If this is a (v)fork/clone child (has a (v)fork/clone parent),
2007 GDB does not yet know about this thread, and must not know about
2008 it until it gets the corresponding (v)fork/clone event. Exclude
2009 this thread from the list. */
2010 if (target_thread_pending_parent (thread) != nullptr)
2011 return;
2013 write_ptid (ptid_s, ptid);
2015 string_xml_appendf (*buffer, "<thread id=\"%s\"", ptid_s);
2017 if (core != -1)
2019 sprintf (core_s, "%d", core);
2020 string_xml_appendf (*buffer, " core=\"%s\"", core_s);
2023 if (name != NULL)
2024 string_xml_appendf (*buffer, " name=\"%s\"", name);
2026 if (handle_status)
2028 char *handle_s = (char *) alloca (handle_len * 2 + 1);
2029 bin2hex (handle, handle_s, handle_len);
2030 string_xml_appendf (*buffer, " handle=\"%s\"", handle_s);
2033 string_xml_appendf (*buffer, "/>\n");
2036 /* Helper for handle_qxfer_threads. Return true on success, false
2037 otherwise. */
2039 static bool
2040 handle_qxfer_threads_proper (std::string *buffer)
2042 *buffer += "<threads>\n";
2044 /* The target may need to access memory and registers (e.g. via
2045 libthread_db) to fetch thread properties. Even if don't need to
2046 stop threads to access memory, we still will need to be able to
2047 access registers, and other ptrace accesses like
2048 PTRACE_GET_THREAD_AREA that require a paused thread. Pause all
2049 threads here, so that we pause each thread at most once for all
2050 accesses. */
2051 if (non_stop)
2052 target_pause_all (true);
2054 for_each_thread ([&] (thread_info *thread)
2056 handle_qxfer_threads_worker (thread, buffer);
2059 if (non_stop)
2060 target_unpause_all (true);
2062 *buffer += "</threads>\n";
2063 return true;
2066 /* Handle qXfer:threads:read. */
2068 static int
2069 handle_qxfer_threads (const char *annex,
2070 gdb_byte *readbuf, const gdb_byte *writebuf,
2071 ULONGEST offset, LONGEST len)
2073 static std::string result;
2075 if (writebuf != NULL)
2076 return -2;
2078 if (annex[0] != '\0')
2079 return -1;
2081 if (offset == 0)
2083 /* When asked for data at offset 0, generate everything and store into
2084 'result'. Successive reads will be served off 'result'. */
2085 result.clear ();
2087 bool res = handle_qxfer_threads_proper (&result);
2089 if (!res)
2090 return -1;
2093 if (offset >= result.length ())
2095 /* We're out of data. */
2096 result.clear ();
2097 return 0;
2100 if (len > result.length () - offset)
2101 len = result.length () - offset;
2103 memcpy (readbuf, result.c_str () + offset, len);
2105 return len;
2108 /* Handle qXfer:traceframe-info:read. */
2110 static int
2111 handle_qxfer_traceframe_info (const char *annex,
2112 gdb_byte *readbuf, const gdb_byte *writebuf,
2113 ULONGEST offset, LONGEST len)
2115 client_state &cs = get_client_state ();
2116 static std::string result;
2118 if (writebuf != NULL)
2119 return -2;
2121 if (!target_running () || annex[0] != '\0' || cs.current_traceframe == -1)
2122 return -1;
2124 if (offset == 0)
2126 /* When asked for data at offset 0, generate everything and
2127 store into 'result'. Successive reads will be served off
2128 'result'. */
2129 result.clear ();
2131 traceframe_read_info (cs.current_traceframe, &result);
2134 if (offset >= result.length ())
2136 /* We're out of data. */
2137 result.clear ();
2138 return 0;
2141 if (len > result.length () - offset)
2142 len = result.length () - offset;
2144 memcpy (readbuf, result.c_str () + offset, len);
2145 return len;
2148 /* Handle qXfer:fdpic:read. */
2150 static int
2151 handle_qxfer_fdpic (const char *annex, gdb_byte *readbuf,
2152 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
2154 if (!the_target->supports_read_loadmap ())
2155 return -2;
2157 if (current_thread == NULL)
2158 return -1;
2160 return the_target->read_loadmap (annex, offset, readbuf, len);
2163 /* Handle qXfer:btrace:read. */
2165 static int
2166 handle_qxfer_btrace (const char *annex,
2167 gdb_byte *readbuf, const gdb_byte *writebuf,
2168 ULONGEST offset, LONGEST len)
2170 client_state &cs = get_client_state ();
2171 static std::string cache;
2172 struct thread_info *thread;
2173 enum btrace_read_type type;
2174 int result;
2176 if (writebuf != NULL)
2177 return -2;
2179 if (cs.general_thread == null_ptid
2180 || cs.general_thread == minus_one_ptid)
2182 strcpy (cs.own_buf, "E.Must select a single thread.");
2183 return -3;
2186 thread = find_thread_ptid (cs.general_thread);
2187 if (thread == NULL)
2189 strcpy (cs.own_buf, "E.No such thread.");
2190 return -3;
2193 if (thread->btrace == NULL)
2195 strcpy (cs.own_buf, "E.Btrace not enabled.");
2196 return -3;
2199 if (strcmp (annex, "all") == 0)
2200 type = BTRACE_READ_ALL;
2201 else if (strcmp (annex, "new") == 0)
2202 type = BTRACE_READ_NEW;
2203 else if (strcmp (annex, "delta") == 0)
2204 type = BTRACE_READ_DELTA;
2205 else
2207 strcpy (cs.own_buf, "E.Bad annex.");
2208 return -3;
2211 if (offset == 0)
2213 cache.clear ();
2217 result = target_read_btrace (thread->btrace, &cache, type);
2218 if (result != 0)
2219 memcpy (cs.own_buf, cache.c_str (), cache.length ());
2221 catch (const gdb_exception_error &exception)
2223 sprintf (cs.own_buf, "E.%s", exception.what ());
2224 result = -1;
2227 if (result != 0)
2228 return -3;
2230 else if (offset > cache.length ())
2232 cache.clear ();
2233 return -3;
2236 if (len > cache.length () - offset)
2237 len = cache.length () - offset;
2239 memcpy (readbuf, cache.c_str () + offset, len);
2241 return len;
2244 /* Handle qXfer:btrace-conf:read. */
2246 static int
2247 handle_qxfer_btrace_conf (const char *annex,
2248 gdb_byte *readbuf, const gdb_byte *writebuf,
2249 ULONGEST offset, LONGEST len)
2251 client_state &cs = get_client_state ();
2252 static std::string cache;
2253 struct thread_info *thread;
2254 int result;
2256 if (writebuf != NULL)
2257 return -2;
2259 if (annex[0] != '\0')
2260 return -1;
2262 if (cs.general_thread == null_ptid
2263 || cs.general_thread == minus_one_ptid)
2265 strcpy (cs.own_buf, "E.Must select a single thread.");
2266 return -3;
2269 thread = find_thread_ptid (cs.general_thread);
2270 if (thread == NULL)
2272 strcpy (cs.own_buf, "E.No such thread.");
2273 return -3;
2276 if (thread->btrace == NULL)
2278 strcpy (cs.own_buf, "E.Btrace not enabled.");
2279 return -3;
2282 if (offset == 0)
2284 cache.clear ();
2288 result = target_read_btrace_conf (thread->btrace, &cache);
2289 if (result != 0)
2290 memcpy (cs.own_buf, cache.c_str (), cache.length ());
2292 catch (const gdb_exception_error &exception)
2294 sprintf (cs.own_buf, "E.%s", exception.what ());
2295 result = -1;
2298 if (result != 0)
2299 return -3;
2301 else if (offset > cache.length ())
2303 cache.clear ();
2304 return -3;
2307 if (len > cache.length () - offset)
2308 len = cache.length () - offset;
2310 memcpy (readbuf, cache.c_str () + offset, len);
2312 return len;
2315 static const struct qxfer qxfer_packets[] =
2317 { "auxv", handle_qxfer_auxv },
2318 { "btrace", handle_qxfer_btrace },
2319 { "btrace-conf", handle_qxfer_btrace_conf },
2320 { "exec-file", handle_qxfer_exec_file},
2321 { "fdpic", handle_qxfer_fdpic},
2322 { "features", handle_qxfer_features },
2323 { "libraries", handle_qxfer_libraries },
2324 { "libraries-svr4", handle_qxfer_libraries_svr4 },
2325 { "osdata", handle_qxfer_osdata },
2326 { "siginfo", handle_qxfer_siginfo },
2327 { "statictrace", handle_qxfer_statictrace },
2328 { "threads", handle_qxfer_threads },
2329 { "traceframe-info", handle_qxfer_traceframe_info },
2332 static int
2333 handle_qxfer (char *own_buf, int packet_len, int *new_packet_len_p)
2335 int i;
2336 char *object;
2337 char *rw;
2338 char *annex;
2339 char *offset;
2341 if (!startswith (own_buf, "qXfer:"))
2342 return 0;
2344 /* Grab the object, r/w and annex. */
2345 if (decode_xfer (own_buf + 6, &object, &rw, &annex, &offset) < 0)
2347 write_enn (own_buf);
2348 return 1;
2351 for (i = 0;
2352 i < sizeof (qxfer_packets) / sizeof (qxfer_packets[0]);
2353 i++)
2355 const struct qxfer *q = &qxfer_packets[i];
2357 if (strcmp (object, q->object) == 0)
2359 if (strcmp (rw, "read") == 0)
2361 unsigned char *data;
2362 int n;
2363 CORE_ADDR ofs;
2364 unsigned int len;
2366 /* Grab the offset and length. */
2367 if (decode_xfer_read (offset, &ofs, &len) < 0)
2369 write_enn (own_buf);
2370 return 1;
2373 /* Read one extra byte, as an indicator of whether there is
2374 more. */
2375 if (len > PBUFSIZ - 2)
2376 len = PBUFSIZ - 2;
2377 data = (unsigned char *) malloc (len + 1);
2378 if (data == NULL)
2380 write_enn (own_buf);
2381 return 1;
2383 n = (*q->xfer) (annex, data, NULL, ofs, len + 1);
2384 if (n == -2)
2386 free (data);
2387 return 0;
2389 else if (n == -3)
2391 /* Preserve error message. */
2393 else if (n < 0)
2394 write_enn (own_buf);
2395 else if (n > len)
2396 *new_packet_len_p = write_qxfer_response (own_buf, data, len, 1);
2397 else
2398 *new_packet_len_p = write_qxfer_response (own_buf, data, n, 0);
2400 free (data);
2401 return 1;
2403 else if (strcmp (rw, "write") == 0)
2405 int n;
2406 unsigned int len;
2407 CORE_ADDR ofs;
2408 unsigned char *data;
2410 strcpy (own_buf, "E00");
2411 data = (unsigned char *) malloc (packet_len - (offset - own_buf));
2412 if (data == NULL)
2414 write_enn (own_buf);
2415 return 1;
2417 if (decode_xfer_write (offset, packet_len - (offset - own_buf),
2418 &ofs, &len, data) < 0)
2420 free (data);
2421 write_enn (own_buf);
2422 return 1;
2425 n = (*q->xfer) (annex, NULL, data, ofs, len);
2426 if (n == -2)
2428 free (data);
2429 return 0;
2431 else if (n == -3)
2433 /* Preserve error message. */
2435 else if (n < 0)
2436 write_enn (own_buf);
2437 else
2438 sprintf (own_buf, "%x", n);
2440 free (data);
2441 return 1;
2444 return 0;
2448 return 0;
2451 /* Compute 32 bit CRC from inferior memory.
2453 On success, return 32 bit CRC.
2454 On failure, return (unsigned long long) -1. */
2456 static unsigned long long
2457 crc32 (CORE_ADDR base, int len, unsigned int crc)
2459 while (len--)
2461 unsigned char byte = 0;
2463 /* Return failure if memory read fails. */
2464 if (read_inferior_memory (base, &byte, 1) != 0)
2465 return (unsigned long long) -1;
2467 crc = xcrc32 (&byte, 1, crc);
2468 base++;
2470 return (unsigned long long) crc;
2473 /* Parse the qMemTags packet request into ADDR and LEN. */
2475 static void
2476 parse_fetch_memtags_request (char *request, CORE_ADDR *addr, size_t *len,
2477 int *type)
2479 gdb_assert (startswith (request, "qMemTags:"));
2481 const char *p = request + strlen ("qMemTags:");
2483 /* Read address and length. */
2484 unsigned int length = 0;
2485 p = decode_m_packet_params (p, addr, &length, ':');
2486 *len = length;
2488 /* Read the tag type. */
2489 ULONGEST tag_type = 0;
2490 p = unpack_varlen_hex (p, &tag_type);
2491 *type = (int) tag_type;
2494 /* Add supported btrace packets to BUF. */
2496 static void
2497 supported_btrace_packets (char *buf)
2499 strcat (buf, ";Qbtrace:bts+");
2500 strcat (buf, ";Qbtrace-conf:bts:size+");
2501 strcat (buf, ";Qbtrace:pt+");
2502 strcat (buf, ";Qbtrace-conf:pt:size+");
2503 strcat (buf, ";Qbtrace-conf:pt:ptwrite+");
2504 strcat (buf, ";Qbtrace-conf:pt:event-tracing+");
2505 strcat (buf, ";Qbtrace:off+");
2506 strcat (buf, ";qXfer:btrace:read+");
2507 strcat (buf, ";qXfer:btrace-conf:read+");
2510 /* Handle all of the extended 'q' packets. */
2512 static void
2513 handle_query (char *own_buf, int packet_len, int *new_packet_len_p)
2515 client_state &cs = get_client_state ();
2516 static owning_intrusive_list<process_info>::iterator process_iter;
2517 static owning_intrusive_list<thread_info>::iterator thread_iter;
2519 auto init_thread_iter = [&] ()
2521 process_iter = all_processes.begin ();
2522 owning_intrusive_list<thread_info> *thread_list;
2524 for (; process_iter != all_processes.end (); ++process_iter)
2526 thread_list = &process_iter->thread_list ();
2527 thread_iter = thread_list->begin ();
2528 if (thread_iter != thread_list->end ())
2529 break;
2531 /* Make sure that there is at least one thread to iterate. */
2532 gdb_assert (process_iter != all_processes.end ());
2533 gdb_assert (thread_iter != thread_list->end ());
2536 auto advance_thread_iter = [&] ()
2538 /* The loop below is written in the natural way as-if we'd always
2539 start at the beginning of the inferior list. This fast forwards
2540 the algorithm to the actual current position. */
2541 owning_intrusive_list<thread_info> *thread_list
2542 = &process_iter->thread_list ();
2543 goto start;
2545 for (; process_iter != all_processes.end (); ++process_iter)
2547 thread_list = &process_iter->thread_list ();
2548 thread_iter = thread_list->begin ();
2549 while (thread_iter != thread_list->end ())
2551 return;
2552 start:
2553 ++thread_iter;
2558 /* Reply the current thread id. */
2559 if (strcmp ("qC", own_buf) == 0 && !disable_packet_qC)
2561 ptid_t ptid;
2562 require_running_or_return (own_buf);
2564 if (cs.general_thread != null_ptid && cs.general_thread != minus_one_ptid)
2565 ptid = cs.general_thread;
2566 else
2568 init_thread_iter ();
2569 ptid = thread_iter->id;
2572 sprintf (own_buf, "QC");
2573 own_buf += 2;
2574 write_ptid (own_buf, ptid);
2575 return;
2578 if (strcmp ("qSymbol::", own_buf) == 0)
2580 scoped_restore_current_thread restore_thread;
2582 /* For qSymbol, GDB only changes the current thread if the
2583 previous current thread was of a different process. So if
2584 the previous thread is gone, we need to pick another one of
2585 the same process. This can happen e.g., if we followed an
2586 exec in a non-leader thread. */
2587 if (current_thread == NULL)
2589 thread_info *any_thread
2590 = find_any_thread_of_pid (cs.general_thread.pid ());
2591 switch_to_thread (any_thread);
2593 /* Just in case, if we didn't find a thread, then bail out
2594 instead of crashing. */
2595 if (current_thread == NULL)
2597 write_enn (own_buf);
2598 return;
2602 /* GDB is suggesting new symbols have been loaded. This may
2603 mean a new shared library has been detected as loaded, so
2604 take the opportunity to check if breakpoints we think are
2605 inserted, still are. Note that it isn't guaranteed that
2606 we'll see this when a shared library is loaded, and nor will
2607 we see this for unloads (although breakpoints in unloaded
2608 libraries shouldn't trigger), as GDB may not find symbols for
2609 the library at all. We also re-validate breakpoints when we
2610 see a second GDB breakpoint for the same address, and or when
2611 we access breakpoint shadows. */
2612 validate_breakpoints ();
2614 if (target_supports_tracepoints ())
2615 tracepoint_look_up_symbols ();
2617 if (current_thread != NULL)
2618 the_target->look_up_symbols ();
2620 strcpy (own_buf, "OK");
2621 return;
2624 if (!disable_packet_qfThreadInfo)
2626 if (strcmp ("qfThreadInfo", own_buf) == 0)
2628 require_running_or_return (own_buf);
2629 init_thread_iter ();
2631 *own_buf++ = 'm';
2632 ptid_t ptid = thread_iter->id;
2633 write_ptid (own_buf, ptid);
2634 advance_thread_iter ();
2635 return;
2638 if (strcmp ("qsThreadInfo", own_buf) == 0)
2640 require_running_or_return (own_buf);
2641 /* We're done if the process iterator hits the end of the
2642 process list. */
2643 if (process_iter != all_processes.end ())
2645 *own_buf++ = 'm';
2646 ptid_t ptid = thread_iter->id;
2647 write_ptid (own_buf, ptid);
2648 advance_thread_iter ();
2649 return;
2651 else
2653 sprintf (own_buf, "l");
2654 return;
2659 if (the_target->supports_read_offsets ()
2660 && strcmp ("qOffsets", own_buf) == 0)
2662 CORE_ADDR text, data;
2664 require_running_or_return (own_buf);
2665 if (the_target->read_offsets (&text, &data))
2666 sprintf (own_buf, "Text=%lX;Data=%lX;Bss=%lX",
2667 (long)text, (long)data, (long)data);
2668 else
2669 write_enn (own_buf);
2671 return;
2674 /* Protocol features query. */
2675 if (startswith (own_buf, "qSupported")
2676 && (own_buf[10] == ':' || own_buf[10] == '\0'))
2678 char *p = &own_buf[10];
2679 int gdb_supports_qRelocInsn = 0;
2681 /* Process each feature being provided by GDB. The first
2682 feature will follow a ':', and latter features will follow
2683 ';'. */
2684 if (*p == ':')
2686 std::vector<std::string> qsupported;
2687 std::vector<const char *> unknowns;
2689 /* Two passes, to avoid nested strtok calls in
2690 target_process_qsupported. */
2691 char *saveptr;
2692 for (p = strtok_r (p + 1, ";", &saveptr);
2693 p != NULL;
2694 p = strtok_r (NULL, ";", &saveptr))
2695 qsupported.emplace_back (p);
2697 for (const std::string &feature : qsupported)
2699 if (feature == "multiprocess+")
2701 /* GDB supports and wants multi-process support if
2702 possible. */
2703 if (target_supports_multi_process ())
2704 cs.multi_process = 1;
2706 else if (feature == "qRelocInsn+")
2708 /* GDB supports relocate instruction requests. */
2709 gdb_supports_qRelocInsn = 1;
2711 else if (feature == "swbreak+")
2713 /* GDB wants us to report whether a trap is caused
2714 by a software breakpoint and for us to handle PC
2715 adjustment if necessary on this target. */
2716 if (target_supports_stopped_by_sw_breakpoint ())
2717 cs.swbreak_feature = 1;
2719 else if (feature == "hwbreak+")
2721 /* GDB wants us to report whether a trap is caused
2722 by a hardware breakpoint. */
2723 if (target_supports_stopped_by_hw_breakpoint ())
2724 cs.hwbreak_feature = 1;
2726 else if (feature == "fork-events+")
2728 /* GDB supports and wants fork events if possible. */
2729 if (target_supports_fork_events ())
2730 cs.report_fork_events = 1;
2732 else if (feature == "vfork-events+")
2734 /* GDB supports and wants vfork events if possible. */
2735 if (target_supports_vfork_events ())
2736 cs.report_vfork_events = 1;
2738 else if (feature == "exec-events+")
2740 /* GDB supports and wants exec events if possible. */
2741 if (target_supports_exec_events ())
2742 cs.report_exec_events = 1;
2744 else if (feature == "vContSupported+")
2745 cs.vCont_supported = 1;
2746 else if (feature == "QThreadEvents+")
2748 else if (feature == "QThreadOptions+")
2750 else if (feature == "no-resumed+")
2752 /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
2753 events. */
2754 report_no_resumed = true;
2756 else if (feature == "memory-tagging+")
2758 /* GDB supports memory tagging features. */
2759 if (target_supports_memory_tagging ())
2760 cs.memory_tagging_feature = true;
2762 else if (feature == "error-message+")
2763 cs.error_message_supported = true;
2764 else
2766 /* Move the unknown features all together. */
2767 unknowns.push_back (feature.c_str ());
2771 /* Give the target backend a chance to process the unknown
2772 features. */
2773 target_process_qsupported (unknowns);
2776 sprintf (own_buf,
2777 "PacketSize=%x;QPassSignals+;QProgramSignals+;"
2778 "QStartupWithShell+;QEnvironmentHexEncoded+;"
2779 "QEnvironmentReset+;QEnvironmentUnset+;"
2780 "QSetWorkingDir+",
2781 PBUFSIZ - 1);
2783 if (target_supports_catch_syscall ())
2784 strcat (own_buf, ";QCatchSyscalls+");
2786 if (the_target->supports_qxfer_libraries_svr4 ())
2787 strcat (own_buf, ";qXfer:libraries-svr4:read+"
2788 ";augmented-libraries-svr4-read+");
2789 else
2791 /* We do not have any hook to indicate whether the non-SVR4 target
2792 backend supports qXfer:libraries:read, so always report it. */
2793 strcat (own_buf, ";qXfer:libraries:read+");
2796 if (the_target->supports_read_auxv ())
2797 strcat (own_buf, ";qXfer:auxv:read+");
2799 if (the_target->supports_qxfer_siginfo ())
2800 strcat (own_buf, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
2802 if (the_target->supports_read_loadmap ())
2803 strcat (own_buf, ";qXfer:fdpic:read+");
2805 /* We always report qXfer:features:read, as targets may
2806 install XML files on a subsequent call to arch_setup.
2807 If we reported to GDB on startup that we don't support
2808 qXfer:feature:read at all, we will never be re-queried. */
2809 strcat (own_buf, ";qXfer:features:read+");
2811 if (cs.transport_is_reliable)
2812 strcat (own_buf, ";QStartNoAckMode+");
2814 if (the_target->supports_qxfer_osdata ())
2815 strcat (own_buf, ";qXfer:osdata:read+");
2817 if (target_supports_multi_process ())
2818 strcat (own_buf, ";multiprocess+");
2820 if (target_supports_fork_events ())
2821 strcat (own_buf, ";fork-events+");
2823 if (target_supports_vfork_events ())
2824 strcat (own_buf, ";vfork-events+");
2826 if (target_supports_exec_events ())
2827 strcat (own_buf, ";exec-events+");
2829 if (target_supports_non_stop ())
2830 strcat (own_buf, ";QNonStop+");
2832 if (target_supports_disable_randomization ())
2833 strcat (own_buf, ";QDisableRandomization+");
2835 strcat (own_buf, ";qXfer:threads:read+");
2837 if (target_supports_tracepoints ())
2839 strcat (own_buf, ";ConditionalTracepoints+");
2840 strcat (own_buf, ";TraceStateVariables+");
2841 strcat (own_buf, ";TracepointSource+");
2842 strcat (own_buf, ";DisconnectedTracing+");
2843 if (gdb_supports_qRelocInsn && target_supports_fast_tracepoints ())
2844 strcat (own_buf, ";FastTracepoints+");
2845 strcat (own_buf, ";StaticTracepoints+");
2846 strcat (own_buf, ";InstallInTrace+");
2847 strcat (own_buf, ";qXfer:statictrace:read+");
2848 strcat (own_buf, ";qXfer:traceframe-info:read+");
2849 strcat (own_buf, ";EnableDisableTracepoints+");
2850 strcat (own_buf, ";QTBuffer:size+");
2851 strcat (own_buf, ";tracenz+");
2854 if (target_supports_hardware_single_step ()
2855 || target_supports_software_single_step () )
2857 strcat (own_buf, ";ConditionalBreakpoints+");
2859 strcat (own_buf, ";BreakpointCommands+");
2861 if (target_supports_agent ())
2862 strcat (own_buf, ";QAgent+");
2864 if (the_target->supports_btrace ())
2865 supported_btrace_packets (own_buf);
2867 if (target_supports_stopped_by_sw_breakpoint ())
2868 strcat (own_buf, ";swbreak+");
2870 if (target_supports_stopped_by_hw_breakpoint ())
2871 strcat (own_buf, ";hwbreak+");
2873 if (the_target->supports_pid_to_exec_file ())
2874 strcat (own_buf, ";qXfer:exec-file:read+");
2876 strcat (own_buf, ";vContSupported+");
2878 gdb_thread_options supported_options = target_supported_thread_options ();
2879 if (supported_options != 0)
2881 char *end_buf = own_buf + strlen (own_buf);
2882 sprintf (end_buf, ";QThreadOptions=%s",
2883 phex_nz (supported_options, sizeof (supported_options)));
2886 strcat (own_buf, ";QThreadEvents+");
2888 strcat (own_buf, ";no-resumed+");
2890 if (target_supports_memory_tagging ())
2891 strcat (own_buf, ";memory-tagging+");
2893 /* Reinitialize components as needed for the new connection. */
2894 hostio_handle_new_gdb_connection ();
2895 target_handle_new_gdb_connection ();
2897 return;
2900 /* Thread-local storage support. */
2901 if (the_target->supports_get_tls_address ()
2902 && startswith (own_buf, "qGetTLSAddr:"))
2904 char *p = own_buf + 12;
2905 CORE_ADDR parts[2], address = 0;
2906 int i, err;
2907 ptid_t ptid = null_ptid;
2909 require_running_or_return (own_buf);
2911 for (i = 0; i < 3; i++)
2913 char *p2;
2914 int len;
2916 if (p == NULL)
2917 break;
2919 p2 = strchr (p, ',');
2920 if (p2)
2922 len = p2 - p;
2923 p2++;
2925 else
2927 len = strlen (p);
2928 p2 = NULL;
2931 if (i == 0)
2932 ptid = read_ptid (p, NULL);
2933 else
2934 decode_address (&parts[i - 1], p, len);
2935 p = p2;
2938 if (p != NULL || i < 3)
2939 err = 1;
2940 else
2942 struct thread_info *thread = find_thread_ptid (ptid);
2944 if (thread == NULL)
2945 err = 2;
2946 else
2947 err = the_target->get_tls_address (thread, parts[0], parts[1],
2948 &address);
2951 if (err == 0)
2953 strcpy (own_buf, paddress(address));
2954 return;
2956 else if (err > 0)
2958 write_enn (own_buf);
2959 return;
2962 /* Otherwise, pretend we do not understand this packet. */
2965 /* Windows OS Thread Information Block address support. */
2966 if (the_target->supports_get_tib_address ()
2967 && startswith (own_buf, "qGetTIBAddr:"))
2969 const char *annex;
2970 int n;
2971 CORE_ADDR tlb;
2972 ptid_t ptid = read_ptid (own_buf + 12, &annex);
2974 n = the_target->get_tib_address (ptid, &tlb);
2975 if (n == 1)
2977 strcpy (own_buf, paddress(tlb));
2978 return;
2980 else if (n == 0)
2982 write_enn (own_buf);
2983 return;
2985 return;
2988 /* Handle "monitor" commands. */
2989 if (startswith (own_buf, "qRcmd,"))
2991 char *mon = (char *) malloc (PBUFSIZ);
2992 int len = strlen (own_buf + 6);
2994 if (mon == NULL)
2996 write_enn (own_buf);
2997 return;
3000 if ((len % 2) != 0
3001 || hex2bin (own_buf + 6, (gdb_byte *) mon, len / 2) != len / 2)
3003 write_enn (own_buf);
3004 free (mon);
3005 return;
3007 mon[len / 2] = '\0';
3009 write_ok (own_buf);
3011 if (the_target->handle_monitor_command (mon) == 0)
3012 /* Default processing. */
3013 handle_monitor_command (mon, own_buf);
3015 free (mon);
3016 return;
3019 if (startswith (own_buf, "qSearch:memory:"))
3021 require_running_or_return (own_buf);
3022 handle_search_memory (own_buf, packet_len);
3023 return;
3026 if (strcmp (own_buf, "qAttached") == 0
3027 || startswith (own_buf, "qAttached:"))
3029 struct process_info *process;
3031 if (own_buf[sizeof ("qAttached") - 1])
3033 int pid = strtoul (own_buf + sizeof ("qAttached:") - 1, NULL, 16);
3034 process = find_process_pid (pid);
3036 else
3038 require_running_or_return (own_buf);
3039 process = current_process ();
3042 if (process == NULL)
3044 write_enn (own_buf);
3045 return;
3048 strcpy (own_buf, process->attached ? "1" : "0");
3049 return;
3052 if (startswith (own_buf, "qCRC:"))
3054 /* CRC check (compare-section). */
3055 const char *comma;
3056 ULONGEST base;
3057 int len;
3058 unsigned long long crc;
3060 require_running_or_return (own_buf);
3061 comma = unpack_varlen_hex (own_buf + 5, &base);
3062 if (*comma++ != ',')
3064 write_enn (own_buf);
3065 return;
3067 len = strtoul (comma, NULL, 16);
3068 crc = crc32 (base, len, 0xffffffff);
3069 /* Check for memory failure. */
3070 if (crc == (unsigned long long) -1)
3072 write_enn (own_buf);
3073 return;
3075 sprintf (own_buf, "C%lx", (unsigned long) crc);
3076 return;
3079 if (handle_qxfer (own_buf, packet_len, new_packet_len_p))
3080 return;
3082 if (target_supports_tracepoints () && handle_tracepoint_query (own_buf))
3083 return;
3085 /* Handle fetch memory tags packets. */
3086 if (startswith (own_buf, "qMemTags:")
3087 && target_supports_memory_tagging ())
3089 gdb::byte_vector tags;
3090 CORE_ADDR addr = 0;
3091 size_t len = 0;
3092 int type = 0;
3094 require_running_or_return (own_buf);
3096 parse_fetch_memtags_request (own_buf, &addr, &len, &type);
3098 bool ret = the_target->fetch_memtags (addr, len, tags, type);
3100 if (ret)
3101 ret = create_fetch_memtags_reply (own_buf, tags);
3103 if (!ret)
3104 write_enn (own_buf);
3106 *new_packet_len_p = strlen (own_buf);
3107 return;
3110 /* Otherwise we didn't know what packet it was. Say we didn't
3111 understand it. */
3112 own_buf[0] = 0;
3115 static void gdb_wants_all_threads_stopped (void);
3116 static void resume (struct thread_resume *actions, size_t n);
3118 /* The callback that is passed to visit_actioned_threads. */
3119 typedef int (visit_actioned_threads_callback_ftype)
3120 (const struct thread_resume *, struct thread_info *);
3122 /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
3123 true if CALLBACK returns true. Returns false if no matching thread
3124 is found or CALLBACK results false.
3125 Note: This function is itself a callback for find_thread. */
3127 static bool
3128 visit_actioned_threads (thread_info *thread,
3129 const struct thread_resume *actions,
3130 size_t num_actions,
3131 visit_actioned_threads_callback_ftype *callback)
3133 for (size_t i = 0; i < num_actions; i++)
3135 const struct thread_resume *action = &actions[i];
3137 if (action->thread == minus_one_ptid
3138 || action->thread == thread->id
3139 || ((action->thread.pid ()
3140 == thread->id.pid ())
3141 && action->thread.lwp () == -1))
3143 if ((*callback) (action, thread))
3144 return true;
3148 return false;
3151 /* Callback for visit_actioned_threads. If the thread has a pending
3152 status to report, report it now. */
3154 static int
3155 handle_pending_status (const struct thread_resume *resumption,
3156 struct thread_info *thread)
3158 client_state &cs = get_client_state ();
3159 if (thread->status_pending_p)
3161 thread->status_pending_p = 0;
3163 cs.last_status = thread->last_status;
3164 cs.last_ptid = thread->id;
3165 prepare_resume_reply (cs.own_buf, cs.last_ptid, cs.last_status);
3166 return 1;
3168 return 0;
3171 /* Parse vCont packets. */
3172 static void
3173 handle_v_cont (char *own_buf)
3175 const char *p;
3176 int n = 0, i = 0;
3177 struct thread_resume *resume_info;
3178 struct thread_resume default_action { null_ptid };
3180 /* Count the number of semicolons in the packet. There should be one
3181 for every action. */
3182 p = &own_buf[5];
3183 while (p)
3185 n++;
3186 p++;
3187 p = strchr (p, ';');
3190 resume_info = (struct thread_resume *) malloc (n * sizeof (resume_info[0]));
3191 if (resume_info == NULL)
3192 goto err;
3194 p = &own_buf[5];
3195 while (*p)
3197 p++;
3199 memset (&resume_info[i], 0, sizeof resume_info[i]);
3201 if (p[0] == 's' || p[0] == 'S')
3202 resume_info[i].kind = resume_step;
3203 else if (p[0] == 'r')
3204 resume_info[i].kind = resume_step;
3205 else if (p[0] == 'c' || p[0] == 'C')
3206 resume_info[i].kind = resume_continue;
3207 else if (p[0] == 't')
3208 resume_info[i].kind = resume_stop;
3209 else
3210 goto err;
3212 if (p[0] == 'S' || p[0] == 'C')
3214 char *q;
3215 int sig = strtol (p + 1, &q, 16);
3216 if (p == q)
3217 goto err;
3218 p = q;
3220 if (!gdb_signal_to_host_p ((enum gdb_signal) sig))
3221 goto err;
3222 resume_info[i].sig = gdb_signal_to_host ((enum gdb_signal) sig);
3224 else if (p[0] == 'r')
3226 ULONGEST addr;
3228 p = unpack_varlen_hex (p + 1, &addr);
3229 resume_info[i].step_range_start = addr;
3231 if (*p != ',')
3232 goto err;
3234 p = unpack_varlen_hex (p + 1, &addr);
3235 resume_info[i].step_range_end = addr;
3237 else
3239 p = p + 1;
3242 if (p[0] == 0)
3244 resume_info[i].thread = minus_one_ptid;
3245 default_action = resume_info[i];
3247 /* Note: we don't increment i here, we'll overwrite this entry
3248 the next time through. */
3250 else if (p[0] == ':')
3252 const char *q;
3253 ptid_t ptid = read_ptid (p + 1, &q);
3255 if (p == q)
3256 goto err;
3257 p = q;
3258 if (p[0] != ';' && p[0] != 0)
3259 goto err;
3261 resume_info[i].thread = ptid;
3263 i++;
3267 if (i < n)
3268 resume_info[i] = default_action;
3270 resume (resume_info, n);
3271 free (resume_info);
3272 return;
3274 err:
3275 write_enn (own_buf);
3276 free (resume_info);
3277 return;
3280 /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
3282 static void
3283 resume (struct thread_resume *actions, size_t num_actions)
3285 client_state &cs = get_client_state ();
3286 if (!non_stop)
3288 /* Check if among the threads that GDB wants actioned, there's
3289 one with a pending status to report. If so, skip actually
3290 resuming/stopping and report the pending event
3291 immediately. */
3293 thread_info *thread_with_status = find_thread ([&] (thread_info *thread)
3295 return visit_actioned_threads (thread, actions, num_actions,
3296 handle_pending_status);
3299 if (thread_with_status != NULL)
3300 return;
3302 enable_async_io ();
3305 the_target->resume (actions, num_actions);
3307 if (non_stop)
3308 write_ok (cs.own_buf);
3309 else
3311 cs.last_ptid = mywait (minus_one_ptid, &cs.last_status, 0, 1);
3313 if (cs.last_status.kind () == TARGET_WAITKIND_NO_RESUMED
3314 && !report_no_resumed)
3316 /* The client does not support this stop reply. At least
3317 return error. */
3318 sprintf (cs.own_buf, "E.No unwaited-for children left.");
3319 disable_async_io ();
3320 return;
3323 if (cs.last_status.kind () != TARGET_WAITKIND_EXITED
3324 && cs.last_status.kind () != TARGET_WAITKIND_SIGNALLED
3325 && cs.last_status.kind () != TARGET_WAITKIND_THREAD_EXITED
3326 && cs.last_status.kind () != TARGET_WAITKIND_NO_RESUMED)
3327 current_thread->last_status = cs.last_status;
3329 /* From the client's perspective, all-stop mode always stops all
3330 threads implicitly (and the target backend has already done
3331 so by now). Tag all threads as "want-stopped", so we don't
3332 resume them implicitly without the client telling us to. */
3333 gdb_wants_all_threads_stopped ();
3334 prepare_resume_reply (cs.own_buf, cs.last_ptid, cs.last_status);
3335 disable_async_io ();
3337 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
3338 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
3339 target_mourn_inferior (cs.last_ptid);
3343 /* Attach to a new program. */
3344 static void
3345 handle_v_attach (char *own_buf)
3347 client_state &cs = get_client_state ();
3349 int pid = strtol (own_buf + 8, NULL, 16);
3353 if (attach_inferior (pid) == 0)
3355 /* Don't report shared library events after attaching, even if
3356 some libraries are preloaded. GDB will always poll the
3357 library list. Avoids the "stopped by shared library event"
3358 notice on the GDB side. */
3359 current_process ()->dlls_changed = false;
3361 if (non_stop)
3363 /* In non-stop, we don't send a resume reply. Stop events
3364 will follow up using the normal notification
3365 mechanism. */
3366 write_ok (own_buf);
3368 else
3369 prepare_resume_reply (own_buf, cs.last_ptid, cs.last_status);
3371 else
3373 /* Not supported. */
3374 own_buf[0] = 0;
3377 catch (const gdb_exception_error &exception)
3379 sprintf (own_buf, "E.%s", exception.what ());
3383 /* Decode an argument from the vRun packet buffer. PTR points to the
3384 first hex-encoded character in the buffer, and LEN is the number of
3385 characters to read from the packet buffer.
3387 If the argument decoding is successful, return a buffer containing the
3388 decoded argument, including a null terminator at the end.
3390 If the argument decoding fails for any reason, return nullptr. */
3392 static gdb::unique_xmalloc_ptr<char>
3393 decode_v_run_arg (const char *ptr, size_t len)
3395 /* Two hex characters are required for each decoded byte. */
3396 if (len % 2 != 0)
3397 return nullptr;
3399 /* The length in bytes needed for the decoded argument. */
3400 len /= 2;
3402 /* Buffer to decode the argument into. The '+ 1' is for the null
3403 terminator we will add. */
3404 char *arg = (char *) xmalloc (len + 1);
3406 /* Decode the argument from the packet and add a null terminator. We do
3407 this within a try block as invalid characters within the PTR buffer
3408 will cause hex2bin to throw an exception. Our caller relies on us
3409 returning nullptr in order to clean up some memory allocations. */
3412 hex2bin (ptr, (gdb_byte *) arg, len);
3413 arg[len] = '\0';
3415 catch (const gdb_exception_error &exception)
3417 return nullptr;
3420 return gdb::unique_xmalloc_ptr<char> (arg);
3423 /* Run a new program. */
3424 static void
3425 handle_v_run (char *own_buf)
3427 client_state &cs = get_client_state ();
3428 char *p, *next_p;
3429 std::vector<char *> new_argv;
3430 gdb::unique_xmalloc_ptr<char> new_program_name;
3431 int i;
3433 for (i = 0, p = own_buf + strlen ("vRun;");
3434 /* Exit condition is at the end of the loop. */;
3435 p = next_p + 1, ++i)
3437 next_p = strchr (p, ';');
3438 if (next_p == NULL)
3439 next_p = p + strlen (p);
3441 if (i == 0 && p == next_p)
3443 /* No program specified. */
3444 gdb_assert (new_program_name == nullptr);
3446 else if (p == next_p)
3448 /* Empty argument. */
3449 new_argv.push_back (xstrdup (""));
3451 else
3453 /* The length of the argument string in the packet. */
3454 size_t len = next_p - p;
3456 gdb::unique_xmalloc_ptr<char> arg = decode_v_run_arg (p, len);
3457 if (arg == nullptr)
3459 write_enn (own_buf);
3460 free_vector_argv (new_argv);
3461 return;
3464 if (i == 0)
3465 new_program_name = std::move (arg);
3466 else
3467 new_argv.push_back (arg.release ());
3469 if (*next_p == '\0')
3470 break;
3473 if (new_program_name == nullptr)
3475 /* GDB didn't specify a program to run. Use the program from the
3476 last run with the new argument list. */
3477 if (program_path.get () == nullptr)
3479 write_enn (own_buf);
3480 free_vector_argv (new_argv);
3481 return;
3484 else
3485 program_path.set (new_program_name.get ());
3487 /* Free the old argv and install the new one. */
3488 free_vector_argv (program_args);
3489 program_args = new_argv;
3493 target_create_inferior (program_path.get (), program_args);
3495 catch (const gdb_exception_error &exception)
3497 sprintf (own_buf, "E.%s", exception.what ());
3498 return;
3501 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
3503 prepare_resume_reply (own_buf, cs.last_ptid, cs.last_status);
3505 /* In non-stop, sending a resume reply doesn't set the general
3506 thread, but GDB assumes a vRun sets it (this is so GDB can
3507 query which is the main thread of the new inferior. */
3508 if (non_stop)
3509 cs.general_thread = cs.last_ptid;
3511 else
3512 write_enn (own_buf);
3515 /* Kill process. */
3516 static void
3517 handle_v_kill (char *own_buf)
3519 client_state &cs = get_client_state ();
3520 int pid;
3521 char *p = &own_buf[6];
3522 if (cs.multi_process)
3523 pid = strtol (p, NULL, 16);
3524 else
3525 pid = signal_pid;
3527 process_info *proc = find_process_pid (pid);
3529 if (proc != nullptr && kill_inferior (proc) == 0)
3531 cs.last_status.set_signalled (GDB_SIGNAL_KILL);
3532 cs.last_ptid = ptid_t (pid);
3533 discard_queued_stop_replies (cs.last_ptid);
3534 write_ok (own_buf);
3536 else
3537 write_enn (own_buf);
3540 /* Handle all of the extended 'v' packets. */
3541 void
3542 handle_v_requests (char *own_buf, int packet_len, int *new_packet_len)
3544 client_state &cs = get_client_state ();
3545 if (!disable_packet_vCont)
3547 if (strcmp (own_buf, "vCtrlC") == 0)
3549 the_target->request_interrupt ();
3550 write_ok (own_buf);
3551 return;
3554 if (startswith (own_buf, "vCont;"))
3556 handle_v_cont (own_buf);
3557 return;
3560 if (startswith (own_buf, "vCont?"))
3562 strcpy (own_buf, "vCont;c;C;t");
3564 if (target_supports_hardware_single_step ()
3565 || target_supports_software_single_step ()
3566 || !cs.vCont_supported)
3568 /* If target supports single step either by hardware or by
3569 software, add actions s and S to the list of supported
3570 actions. On the other hand, if GDB doesn't request the
3571 supported vCont actions in qSupported packet, add s and
3572 S to the list too. */
3573 own_buf = own_buf + strlen (own_buf);
3574 strcpy (own_buf, ";s;S");
3577 if (target_supports_range_stepping ())
3579 own_buf = own_buf + strlen (own_buf);
3580 strcpy (own_buf, ";r");
3582 return;
3586 if (startswith (own_buf, "vFile:")
3587 && handle_vFile (own_buf, packet_len, new_packet_len))
3588 return;
3590 if (startswith (own_buf, "vAttach;"))
3592 if ((!extended_protocol || !cs.multi_process) && target_running ())
3594 fprintf (stderr, "Already debugging a process\n");
3595 write_enn (own_buf);
3596 return;
3598 handle_v_attach (own_buf);
3599 return;
3602 if (startswith (own_buf, "vRun;"))
3604 if ((!extended_protocol || !cs.multi_process) && target_running ())
3606 fprintf (stderr, "Already debugging a process\n");
3607 write_enn (own_buf);
3608 return;
3610 handle_v_run (own_buf);
3611 return;
3614 if (startswith (own_buf, "vKill;"))
3616 if (!target_running ())
3618 fprintf (stderr, "No process to kill\n");
3619 write_enn (own_buf);
3620 return;
3622 handle_v_kill (own_buf);
3623 return;
3626 if (handle_notif_ack (own_buf, packet_len))
3627 return;
3629 /* Otherwise we didn't know what packet it was. Say we didn't
3630 understand it. */
3631 own_buf[0] = 0;
3632 return;
3635 /* Resume thread and wait for another event. In non-stop mode,
3636 don't really wait here, but return immediately to the event
3637 loop. */
3638 static void
3639 myresume (char *own_buf, int step, int sig)
3641 client_state &cs = get_client_state ();
3642 struct thread_resume resume_info[2];
3643 int n = 0;
3644 int valid_cont_thread;
3646 valid_cont_thread = (cs.cont_thread != null_ptid
3647 && cs.cont_thread != minus_one_ptid);
3649 if (step || sig || valid_cont_thread)
3651 resume_info[0].thread = current_thread->id;
3652 if (step)
3653 resume_info[0].kind = resume_step;
3654 else
3655 resume_info[0].kind = resume_continue;
3656 resume_info[0].sig = sig;
3657 n++;
3660 if (!valid_cont_thread)
3662 resume_info[n].thread = minus_one_ptid;
3663 resume_info[n].kind = resume_continue;
3664 resume_info[n].sig = 0;
3665 n++;
3668 resume (resume_info, n);
3671 /* Callback for for_each_thread. Make a new stop reply for each
3672 stopped thread. */
3674 static void
3675 queue_stop_reply_callback (thread_info *thread)
3677 /* For now, assume targets that don't have this callback also don't
3678 manage the thread's last_status field. */
3679 if (!the_target->supports_thread_stopped ())
3681 struct vstop_notif *new_notif = new struct vstop_notif;
3683 new_notif->ptid = thread->id;
3684 new_notif->status = thread->last_status;
3685 /* Pass the last stop reply back to GDB, but don't notify
3686 yet. */
3687 notif_event_enque (&notif_stop, new_notif);
3689 else
3691 if (target_thread_stopped (thread))
3693 threads_debug_printf
3694 ("Reporting thread %s as already stopped with %s",
3695 target_pid_to_str (thread->id).c_str (),
3696 thread->last_status.to_string ().c_str ());
3698 gdb_assert (thread->last_status.kind () != TARGET_WAITKIND_IGNORE);
3700 /* Pass the last stop reply back to GDB, but don't notify
3701 yet. */
3702 queue_stop_reply (thread->id, thread->last_status);
3707 /* Set this inferior threads's state as "want-stopped". We won't
3708 resume this thread until the client gives us another action for
3709 it. */
3711 static void
3712 gdb_wants_thread_stopped (thread_info *thread)
3714 thread->last_resume_kind = resume_stop;
3716 if (thread->last_status.kind () == TARGET_WAITKIND_IGNORE)
3718 /* Most threads are stopped implicitly (all-stop); tag that with
3719 signal 0. */
3720 thread->last_status.set_stopped (GDB_SIGNAL_0);
3724 /* Set all threads' states as "want-stopped". */
3726 static void
3727 gdb_wants_all_threads_stopped (void)
3729 for_each_thread (gdb_wants_thread_stopped);
3732 /* Callback for for_each_thread. If the thread is stopped with an
3733 interesting event, mark it as having a pending event. */
3735 static void
3736 set_pending_status_callback (thread_info *thread)
3738 if (thread->last_status.kind () != TARGET_WAITKIND_STOPPED
3739 || (thread->last_status.sig () != GDB_SIGNAL_0
3740 /* A breakpoint, watchpoint or finished step from a previous
3741 GDB run isn't considered interesting for a new GDB run.
3742 If we left those pending, the new GDB could consider them
3743 random SIGTRAPs. This leaves out real async traps. We'd
3744 have to peek into the (target-specific) siginfo to
3745 distinguish those. */
3746 && thread->last_status.sig () != GDB_SIGNAL_TRAP))
3747 thread->status_pending_p = 1;
3750 /* Status handler for the '?' packet. */
3752 static void
3753 handle_status (char *own_buf)
3755 client_state &cs = get_client_state ();
3757 /* GDB is connected, don't forward events to the target anymore. */
3758 for_each_process ([] (process_info *process) {
3759 process->gdb_detached = 0;
3762 /* In non-stop mode, we must send a stop reply for each stopped
3763 thread. In all-stop mode, just send one for the first stopped
3764 thread we find. */
3766 if (non_stop)
3768 for_each_thread (queue_stop_reply_callback);
3770 /* The first is sent immediately. OK is sent if there is no
3771 stopped thread, which is the same handling of the vStopped
3772 packet (by design). */
3773 notif_write_event (&notif_stop, cs.own_buf);
3775 else
3777 thread_info *thread = NULL;
3779 target_pause_all (false);
3780 target_stabilize_threads ();
3781 gdb_wants_all_threads_stopped ();
3783 /* We can only report one status, but we might be coming out of
3784 non-stop -- if more than one thread is stopped with
3785 interesting events, leave events for the threads we're not
3786 reporting now pending. They'll be reported the next time the
3787 threads are resumed. Start by marking all interesting events
3788 as pending. */
3789 for_each_thread (set_pending_status_callback);
3791 /* Prefer the last thread that reported an event to GDB (even if
3792 that was a GDB_SIGNAL_TRAP). */
3793 if (cs.last_status.kind () != TARGET_WAITKIND_IGNORE
3794 && cs.last_status.kind () != TARGET_WAITKIND_EXITED
3795 && cs.last_status.kind () != TARGET_WAITKIND_SIGNALLED)
3796 thread = find_thread_ptid (cs.last_ptid);
3798 /* If the last event thread is not found for some reason, look
3799 for some other thread that might have an event to report. */
3800 if (thread == NULL)
3801 thread = find_thread ([] (thread_info *thr_arg)
3803 return thr_arg->status_pending_p;
3806 /* If we're still out of luck, simply pick the first thread in
3807 the thread list. */
3808 if (thread == NULL)
3809 thread = get_first_thread ();
3811 if (thread != NULL)
3813 struct thread_info *tp = (struct thread_info *) thread;
3815 /* We're reporting this event, so it's no longer
3816 pending. */
3817 tp->status_pending_p = 0;
3819 /* GDB assumes the current thread is the thread we're
3820 reporting the status for. */
3821 cs.general_thread = thread->id;
3822 set_desired_thread ();
3824 gdb_assert (tp->last_status.kind () != TARGET_WAITKIND_IGNORE);
3825 prepare_resume_reply (own_buf, tp->id, tp->last_status);
3827 else
3828 strcpy (own_buf, "W00");
3832 static void
3833 gdbserver_version (void)
3835 printf ("GNU gdbserver %s%s\n"
3836 "Copyright (C) 2024 Free Software Foundation, Inc.\n"
3837 "gdbserver is free software, covered by the "
3838 "GNU General Public License.\n"
3839 "This gdbserver was configured as \"%s\"\n",
3840 PKGVERSION, version, host_name);
3843 static void
3844 gdbserver_usage (FILE *stream)
3846 fprintf (stream, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
3847 "\tgdbserver [OPTIONS] --attach COMM PID\n"
3848 "\tgdbserver [OPTIONS] --multi COMM\n"
3849 "\n"
3850 "COMM may either be a tty device (for serial debugging),\n"
3851 "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
3852 "stdin/stdout of gdbserver.\n"
3853 "PROG is the executable program. ARGS are arguments passed to inferior.\n"
3854 "PID is the process ID to attach to, when --attach is specified.\n"
3855 "\n"
3856 "Operating modes:\n"
3857 "\n"
3858 " --attach Attach to running process PID.\n"
3859 " --multi Start server without a specific program, and\n"
3860 " only quit when explicitly commanded.\n"
3861 " --once Exit after the first connection has closed.\n"
3862 " --help Print this message and then exit.\n"
3863 " --version Display version information and exit.\n"
3864 "\n"
3865 "Other options:\n"
3866 "\n"
3867 " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
3868 " --disable-randomization\n"
3869 " Run PROG with address space randomization disabled.\n"
3870 " --no-disable-randomization\n"
3871 " Don't disable address space randomization when\n"
3872 " starting PROG.\n"
3873 " --startup-with-shell\n"
3874 " Start PROG using a shell. I.e., execs a shell that\n"
3875 " then execs PROG. (default)\n"
3876 " --no-startup-with-shell\n"
3877 " Exec PROG directly instead of using a shell.\n"
3878 " Disables argument globbing and variable substitution\n"
3879 " on UNIX-like systems.\n"
3880 "\n"
3881 "Debug options:\n"
3882 "\n"
3883 " --debug[=OPT1,OPT2,...]\n"
3884 " Enable debugging output.\n"
3885 " Options:\n"
3886 " all, threads, event-loop, remote\n"
3887 " With no options, 'threads' is assumed.\n"
3888 " Prefix an option with '-' to disable\n"
3889 " debugging of that component.\n"
3890 " --debug-format=OPT1[,OPT2,...]\n"
3891 " Specify extra content in debugging output.\n"
3892 " Options:\n"
3893 " all\n"
3894 " none\n"
3895 " timestamp\n"
3896 " --disable-packet=OPT1[,OPT2,...]\n"
3897 " Disable support for RSP packets or features.\n"
3898 " Options:\n"
3899 " vCont, T, Tthread, qC, qfThreadInfo and \n"
3900 " threads (disable all threading packets).\n"
3901 "\n"
3902 "For more information, consult the GDB manual (available as on-line \n"
3903 "info or a printed manual).\n");
3904 if (REPORT_BUGS_TO[0] && stream == stdout)
3905 fprintf (stream, "Report bugs to \"%s\".\n", REPORT_BUGS_TO);
3908 static void
3909 gdbserver_show_disableable (FILE *stream)
3911 fprintf (stream, "Disableable packets:\n"
3912 " vCont \tAll vCont packets\n"
3913 " qC \tQuerying the current thread\n"
3914 " qfThreadInfo\tThread listing\n"
3915 " Tthread \tPassing the thread specifier in the "
3916 "T stop reply packet\n"
3917 " threads \tAll of the above\n"
3918 " T \tAll 'T' packets\n");
3921 /* Start up the event loop. This is the entry point to the event
3922 loop. */
3924 static void
3925 start_event_loop ()
3927 /* Loop until there is nothing to do. This is the entry point to
3928 the event loop engine. If nothing is ready at this time, wait
3929 for something to happen (via wait_for_event), then process it.
3930 Return when there are no longer event sources to wait for. */
3932 keep_processing_events = true;
3933 while (keep_processing_events)
3935 /* Any events already waiting in the queue? */
3936 int res = gdb_do_one_event ();
3938 /* Was there an error? */
3939 if (res == -1)
3940 break;
3943 /* We are done with the event loop. There are no more event sources
3944 to listen to. So we exit gdbserver. */
3947 static void
3948 kill_inferior_callback (process_info *process)
3950 kill_inferior (process);
3951 discard_queued_stop_replies (ptid_t (process->pid));
3954 /* Call this when exiting gdbserver with possible inferiors that need
3955 to be killed or detached from. */
3957 static void
3958 detach_or_kill_for_exit (void)
3960 /* First print a list of the inferiors we will be killing/detaching.
3961 This is to assist the user, for example, in case the inferior unexpectedly
3962 dies after we exit: did we screw up or did the inferior exit on its own?
3963 Having this info will save some head-scratching. */
3965 if (have_started_inferiors_p ())
3967 fprintf (stderr, "Killing process(es):");
3969 for_each_process ([] (process_info *process) {
3970 if (!process->attached)
3971 fprintf (stderr, " %d", process->pid);
3974 fprintf (stderr, "\n");
3976 if (have_attached_inferiors_p ())
3978 fprintf (stderr, "Detaching process(es):");
3980 for_each_process ([] (process_info *process) {
3981 if (process->attached)
3982 fprintf (stderr, " %d", process->pid);
3985 fprintf (stderr, "\n");
3988 /* Now we can kill or detach the inferiors. */
3989 for_each_process ([] (process_info *process) {
3990 int pid = process->pid;
3992 if (process->attached)
3993 detach_inferior (process);
3994 else
3995 kill_inferior (process);
3997 discard_queued_stop_replies (ptid_t (pid));
4001 /* Value that will be passed to exit(3) when gdbserver exits. */
4002 static int exit_code;
4004 /* Wrapper for detach_or_kill_for_exit that catches and prints
4005 errors. */
4007 static void
4008 detach_or_kill_for_exit_cleanup ()
4012 detach_or_kill_for_exit ();
4014 catch (const gdb_exception &exception)
4016 fflush (stdout);
4017 fprintf (stderr, "Detach or kill failed: %s\n",
4018 exception.what ());
4019 exit_code = 1;
4023 #if GDB_SELF_TEST
4025 namespace selftests {
4027 static void
4028 test_memory_tagging_functions (void)
4030 /* Setup testing. */
4031 gdb::char_vector packet;
4032 gdb::byte_vector tags, bv;
4033 std::string expected;
4034 packet.resize (32000);
4035 CORE_ADDR addr;
4036 size_t len;
4037 int type;
4039 /* Test parsing a qMemTags request. */
4041 /* Valid request, addr, len and type updated. */
4042 addr = 0xff;
4043 len = 255;
4044 type = 255;
4045 strcpy (packet.data (), "qMemTags:0,0:0");
4046 parse_fetch_memtags_request (packet.data (), &addr, &len, &type);
4047 SELF_CHECK (addr == 0 && len == 0 && type == 0);
4049 /* Valid request, addr, len and type updated. */
4050 addr = 0;
4051 len = 0;
4052 type = 0;
4053 strcpy (packet.data (), "qMemTags:deadbeef,ff:5");
4054 parse_fetch_memtags_request (packet.data (), &addr, &len, &type);
4055 SELF_CHECK (addr == 0xdeadbeef && len == 255 && type == 5);
4057 /* Test creating a qMemTags reply. */
4059 /* Non-empty tag data. */
4060 bv.resize (0);
4062 for (int i = 0; i < 5; i++)
4063 bv.push_back (i);
4065 expected = "m0001020304";
4066 SELF_CHECK (create_fetch_memtags_reply (packet.data (), bv) == true);
4067 SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
4069 /* Test parsing a QMemTags request. */
4071 /* Valid request and empty tag data: addr, len, type and tags updated. */
4072 addr = 0xff;
4073 len = 255;
4074 type = 255;
4075 tags.resize (5);
4076 strcpy (packet.data (), "QMemTags:0,0:0:");
4077 SELF_CHECK (parse_store_memtags_request (packet.data (),
4078 &addr, &len, tags, &type) == true);
4079 SELF_CHECK (addr == 0 && len == 0 && type == 0 && tags.size () == 0);
4081 /* Valid request and non-empty tag data: addr, len, type
4082 and tags updated. */
4083 addr = 0;
4084 len = 0;
4085 type = 0;
4086 tags.resize (0);
4087 strcpy (packet.data (),
4088 "QMemTags:deadbeef,ff:5:0001020304");
4089 SELF_CHECK (parse_store_memtags_request (packet.data (), &addr, &len, tags,
4090 &type) == true);
4091 SELF_CHECK (addr == 0xdeadbeef && len == 255 && type == 5
4092 && tags.size () == 5);
4095 } // namespace selftests
4096 #endif /* GDB_SELF_TEST */
4098 /* Main function. This is called by the real "main" function,
4099 wrapped in a TRY_CATCH that handles any uncaught exceptions. */
4101 [[noreturn]] static void
4102 captured_main (int argc, char *argv[])
4104 int bad_attach;
4105 int pid;
4106 char *arg_end;
4107 const char *port = NULL;
4108 char **next_arg = &argv[1];
4109 volatile int multi_mode = 0;
4110 volatile int attach = 0;
4111 int was_running;
4112 bool selftest = false;
4113 #if GDB_SELF_TEST
4114 std::vector<const char *> selftest_filters;
4116 selftests::register_test ("remote_memory_tagging",
4117 selftests::test_memory_tagging_functions);
4118 #endif
4120 current_directory = getcwd (NULL, 0);
4121 client_state &cs = get_client_state ();
4123 if (current_directory == NULL)
4125 error (_("Could not find current working directory: %s"),
4126 safe_strerror (errno));
4129 while (*next_arg != NULL && **next_arg == '-')
4131 if (strcmp (*next_arg, "--version") == 0)
4133 gdbserver_version ();
4134 exit (0);
4136 else if (strcmp (*next_arg, "--help") == 0)
4138 gdbserver_usage (stdout);
4139 exit (0);
4141 else if (strcmp (*next_arg, "--attach") == 0)
4142 attach = 1;
4143 else if (strcmp (*next_arg, "--multi") == 0)
4144 multi_mode = 1;
4145 else if (strcmp (*next_arg, "--wrapper") == 0)
4147 char **tmp;
4149 next_arg++;
4151 tmp = next_arg;
4152 while (*next_arg != NULL && strcmp (*next_arg, "--") != 0)
4154 wrapper_argv += *next_arg;
4155 wrapper_argv += ' ';
4156 next_arg++;
4159 if (!wrapper_argv.empty ())
4161 /* Erase the last whitespace. */
4162 wrapper_argv.erase (wrapper_argv.end () - 1);
4165 if (next_arg == tmp || *next_arg == NULL)
4167 gdbserver_usage (stderr);
4168 exit (1);
4171 /* Consume the "--". */
4172 *next_arg = NULL;
4174 else if (startswith (*next_arg, "--debug="))
4178 parse_debug_options ((*next_arg) + sizeof ("--debug=") - 1);
4180 catch (const gdb_exception_error &exception)
4182 fflush (stdout);
4183 fprintf (stderr, "gdbserver: %s\n", exception.what ());
4184 exit (1);
4187 else if (strcmp (*next_arg, "--debug") == 0)
4191 parse_debug_options ("");
4193 catch (const gdb_exception_error &exception)
4195 fflush (stdout);
4196 fprintf (stderr, "gdbserver: %s\n", exception.what ());
4197 exit (1);
4200 else if (startswith (*next_arg, "--debug-format="))
4202 std::string error_msg
4203 = parse_debug_format_options ((*next_arg)
4204 + sizeof ("--debug-format=") - 1, 0);
4206 if (!error_msg.empty ())
4208 fprintf (stderr, "%s", error_msg.c_str ());
4209 exit (1);
4212 else if (startswith (*next_arg, "--debug-file="))
4213 debug_set_output ((*next_arg) + sizeof ("--debug-file=") -1);
4214 else if (strcmp (*next_arg, "--disable-packet") == 0)
4216 gdbserver_show_disableable (stdout);
4217 exit (0);
4219 else if (startswith (*next_arg, "--disable-packet="))
4221 char *packets = *next_arg += sizeof ("--disable-packet=") - 1;
4222 char *saveptr;
4223 for (char *tok = strtok_r (packets, ",", &saveptr);
4224 tok != NULL;
4225 tok = strtok_r (NULL, ",", &saveptr))
4227 if (strcmp ("vCont", tok) == 0)
4228 disable_packet_vCont = true;
4229 else if (strcmp ("Tthread", tok) == 0)
4230 disable_packet_Tthread = true;
4231 else if (strcmp ("qC", tok) == 0)
4232 disable_packet_qC = true;
4233 else if (strcmp ("qfThreadInfo", tok) == 0)
4234 disable_packet_qfThreadInfo = true;
4235 else if (strcmp ("T", tok) == 0)
4236 disable_packet_T = true;
4237 else if (strcmp ("threads", tok) == 0)
4239 disable_packet_vCont = true;
4240 disable_packet_Tthread = true;
4241 disable_packet_qC = true;
4242 disable_packet_qfThreadInfo = true;
4244 else
4246 fprintf (stderr, "Don't know how to disable \"%s\".\n\n",
4247 tok);
4248 gdbserver_show_disableable (stderr);
4249 exit (1);
4253 else if (strcmp (*next_arg, "-") == 0)
4255 /* "-" specifies a stdio connection and is a form of port
4256 specification. */
4257 port = STDIO_CONNECTION_NAME;
4259 /* Implying --once here prevents a hang after stdin has been closed. */
4260 run_once = true;
4262 next_arg++;
4263 break;
4265 else if (strcmp (*next_arg, "--disable-randomization") == 0)
4266 cs.disable_randomization = 1;
4267 else if (strcmp (*next_arg, "--no-disable-randomization") == 0)
4268 cs.disable_randomization = 0;
4269 else if (strcmp (*next_arg, "--startup-with-shell") == 0)
4270 startup_with_shell = true;
4271 else if (strcmp (*next_arg, "--no-startup-with-shell") == 0)
4272 startup_with_shell = false;
4273 else if (strcmp (*next_arg, "--once") == 0)
4274 run_once = true;
4275 else if (strcmp (*next_arg, "--selftest") == 0)
4276 selftest = true;
4277 else if (startswith (*next_arg, "--selftest="))
4279 selftest = true;
4281 #if GDB_SELF_TEST
4282 const char *filter = *next_arg + strlen ("--selftest=");
4283 if (*filter == '\0')
4285 fprintf (stderr, _("Error: selftest filter is empty.\n"));
4286 exit (1);
4289 selftest_filters.push_back (filter);
4290 #endif
4292 else
4294 fprintf (stderr, "Unknown argument: %s\n", *next_arg);
4295 exit (1);
4298 next_arg++;
4299 continue;
4302 if (port == NULL)
4304 port = *next_arg;
4305 next_arg++;
4307 if ((port == NULL || (!attach && !multi_mode && *next_arg == NULL))
4308 && !selftest)
4310 gdbserver_usage (stderr);
4311 exit (1);
4314 /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
4315 opened by remote_prepare. */
4316 notice_open_fds ();
4318 save_original_signals_state (false);
4320 /* We need to know whether the remote connection is stdio before
4321 starting the inferior. Inferiors created in this scenario have
4322 stdin,stdout redirected. So do this here before we call
4323 start_inferior. */
4324 if (port != NULL)
4325 remote_prepare (port);
4327 bad_attach = 0;
4328 pid = 0;
4330 /* --attach used to come after PORT, so allow it there for
4331 compatibility. */
4332 if (*next_arg != NULL && strcmp (*next_arg, "--attach") == 0)
4334 attach = 1;
4335 next_arg++;
4338 if (attach
4339 && (*next_arg == NULL
4340 || (*next_arg)[0] == '\0'
4341 || (pid = strtoul (*next_arg, &arg_end, 0)) == 0
4342 || *arg_end != '\0'
4343 || next_arg[1] != NULL))
4344 bad_attach = 1;
4346 if (bad_attach)
4348 gdbserver_usage (stderr);
4349 exit (1);
4352 /* Gather information about the environment. */
4353 our_environ = gdb_environ::from_host_environ ();
4355 initialize_async_io ();
4356 initialize_low ();
4357 have_job_control ();
4358 if (target_supports_tracepoints ())
4359 initialize_tracepoint ();
4361 mem_buf = (unsigned char *) xmalloc (PBUFSIZ);
4363 if (selftest)
4365 #if GDB_SELF_TEST
4366 selftests::run_tests (selftest_filters);
4367 #else
4368 printf (_("Selftests have been disabled for this build.\n"));
4369 #endif
4370 throw_quit ("Quit");
4373 if (pid == 0 && *next_arg != NULL)
4375 int i, n;
4377 n = argc - (next_arg - argv);
4378 program_path.set (next_arg[0]);
4379 for (i = 1; i < n; i++)
4380 program_args.push_back (xstrdup (next_arg[i]));
4382 /* Wait till we are at first instruction in program. */
4383 target_create_inferior (program_path.get (), program_args);
4385 /* We are now (hopefully) stopped at the first instruction of
4386 the target process. This assumes that the target process was
4387 successfully created. */
4389 else if (pid != 0)
4391 if (attach_inferior (pid) == -1)
4392 error ("Attaching not supported on this target");
4394 /* Otherwise succeeded. */
4396 else
4398 cs.last_status.set_exited (0);
4399 cs.last_ptid = minus_one_ptid;
4402 SCOPE_EXIT { detach_or_kill_for_exit_cleanup (); };
4404 /* Don't report shared library events on the initial connection,
4405 even if some libraries are preloaded. Avoids the "stopped by
4406 shared library event" notice on gdb side. */
4407 if (current_thread != nullptr)
4408 current_process ()->dlls_changed = false;
4410 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
4411 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
4412 was_running = 0;
4413 else
4414 was_running = 1;
4416 if (!was_running && !multi_mode)
4417 error ("No program to debug");
4419 while (1)
4421 cs.noack_mode = 0;
4422 cs.multi_process = 0;
4423 cs.report_fork_events = 0;
4424 cs.report_vfork_events = 0;
4425 cs.report_exec_events = 0;
4426 /* Be sure we're out of tfind mode. */
4427 cs.current_traceframe = -1;
4428 cs.cont_thread = null_ptid;
4429 cs.swbreak_feature = 0;
4430 cs.hwbreak_feature = 0;
4431 cs.vCont_supported = 0;
4432 cs.memory_tagging_feature = false;
4433 cs.error_message_supported = false;
4435 remote_open (port);
4439 /* Wait for events. This will return when all event sources
4440 are removed from the event loop. */
4441 start_event_loop ();
4443 /* If an exit was requested (using the "monitor exit"
4444 command), terminate now. */
4445 if (exit_requested)
4446 throw_quit ("Quit");
4448 /* The only other way to get here is for getpkt to fail:
4450 - If --once was specified, we're done.
4452 - If not in extended-remote mode, and we're no longer
4453 debugging anything, simply exit: GDB has disconnected
4454 after processing the last process exit.
4456 - Otherwise, close the connection and reopen it at the
4457 top of the loop. */
4458 if (run_once || (!extended_protocol && !target_running ()))
4459 throw_quit ("Quit");
4461 fprintf (stderr,
4462 "Remote side has terminated connection. "
4463 "GDBserver will reopen the connection.\n");
4465 /* Get rid of any pending statuses. An eventual reconnection
4466 (by the same GDB instance or another) will refresh all its
4467 state from scratch. */
4468 discard_queued_stop_replies (minus_one_ptid);
4469 for_each_thread ([] (thread_info *thread)
4471 thread->status_pending_p = 0;
4474 if (tracing)
4476 if (disconnected_tracing)
4478 /* Try to enable non-stop/async mode, so we we can
4479 both wait for an async socket accept, and handle
4480 async target events simultaneously. There's also
4481 no point either in having the target always stop
4482 all threads, when we're going to pass signals
4483 down without informing GDB. */
4484 if (!non_stop)
4486 if (the_target->start_non_stop (true))
4487 non_stop = 1;
4489 /* Detaching implicitly resumes all threads;
4490 simply disconnecting does not. */
4493 else
4495 fprintf (stderr,
4496 "Disconnected tracing disabled; "
4497 "stopping trace run.\n");
4498 stop_tracing ();
4502 catch (const gdb_exception_error &exception)
4504 fflush (stdout);
4505 fprintf (stderr, "gdbserver: %s\n", exception.what ());
4507 if (response_needed)
4509 write_enn (cs.own_buf);
4510 putpkt (cs.own_buf);
4513 if (run_once)
4514 throw_quit ("Quit");
4519 /* Main function. */
4522 main (int argc, char *argv[])
4524 setlocale (LC_CTYPE, "");
4528 captured_main (argc, argv);
4530 catch (const gdb_exception &exception)
4532 if (exception.reason == RETURN_ERROR)
4534 fflush (stdout);
4535 fprintf (stderr, "%s\n", exception.what ());
4536 fprintf (stderr, "Exiting\n");
4537 exit_code = 1;
4540 exit (exit_code);
4543 gdb_assert_not_reached ("captured_main should never return");
4546 /* Process options coming from Z packets for a breakpoint. PACKET is
4547 the packet buffer. *PACKET is updated to point to the first char
4548 after the last processed option. */
4550 static void
4551 process_point_options (struct gdb_breakpoint *bp, const char **packet)
4553 const char *dataptr = *packet;
4554 int persist;
4556 /* Check if data has the correct format. */
4557 if (*dataptr != ';')
4558 return;
4560 dataptr++;
4562 while (*dataptr)
4564 if (*dataptr == ';')
4565 ++dataptr;
4567 if (*dataptr == 'X')
4569 /* Conditional expression. */
4570 threads_debug_printf ("Found breakpoint condition.");
4571 if (!add_breakpoint_condition (bp, &dataptr))
4572 dataptr = strchrnul (dataptr, ';');
4574 else if (startswith (dataptr, "cmds:"))
4576 dataptr += strlen ("cmds:");
4577 threads_debug_printf ("Found breakpoint commands %s.", dataptr);
4578 persist = (*dataptr == '1');
4579 dataptr += 2;
4580 if (add_breakpoint_commands (bp, &dataptr, persist))
4581 dataptr = strchrnul (dataptr, ';');
4583 else
4585 fprintf (stderr, "Unknown token %c, ignoring.\n",
4586 *dataptr);
4587 /* Skip tokens until we find one that we recognize. */
4588 dataptr = strchrnul (dataptr, ';');
4591 *packet = dataptr;
4594 /* Event loop callback that handles a serial event. The first byte in
4595 the serial buffer gets us here. We expect characters to arrive at
4596 a brisk pace, so we read the rest of the packet with a blocking
4597 getpkt call. */
4599 static int
4600 process_serial_event (void)
4602 client_state &cs = get_client_state ();
4603 int signal;
4604 unsigned int len;
4605 CORE_ADDR mem_addr;
4606 unsigned char sig;
4607 int packet_len;
4608 int new_packet_len = -1;
4610 disable_async_io ();
4612 response_needed = false;
4613 packet_len = getpkt (cs.own_buf);
4614 if (packet_len <= 0)
4616 remote_close ();
4617 /* Force an event loop break. */
4618 return -1;
4620 response_needed = true;
4622 char ch = cs.own_buf[0];
4623 switch (ch)
4625 case 'q':
4626 handle_query (cs.own_buf, packet_len, &new_packet_len);
4627 break;
4628 case 'Q':
4629 handle_general_set (cs.own_buf);
4630 break;
4631 case 'D':
4632 handle_detach (cs.own_buf);
4633 break;
4634 case '!':
4635 extended_protocol = true;
4636 write_ok (cs.own_buf);
4637 break;
4638 case '?':
4639 handle_status (cs.own_buf);
4640 break;
4641 case 'H':
4642 if (cs.own_buf[1] == 'c' || cs.own_buf[1] == 'g' || cs.own_buf[1] == 's')
4644 require_running_or_break (cs.own_buf);
4646 ptid_t thread_id = read_ptid (&cs.own_buf[2], NULL);
4648 if (thread_id == null_ptid || thread_id == minus_one_ptid)
4649 thread_id = null_ptid;
4650 else if (thread_id.is_pid ())
4652 /* The ptid represents a pid. */
4653 thread_info *thread = find_any_thread_of_pid (thread_id.pid ());
4655 if (thread == NULL)
4657 write_enn (cs.own_buf);
4658 break;
4661 thread_id = thread->id;
4663 else
4665 /* The ptid represents a lwp/tid. */
4666 if (find_thread_ptid (thread_id) == NULL)
4668 write_enn (cs.own_buf);
4669 break;
4673 if (cs.own_buf[1] == 'g')
4675 if (thread_id == null_ptid)
4677 /* GDB is telling us to choose any thread. Check if
4678 the currently selected thread is still valid. If
4679 it is not, select the first available. */
4680 thread_info *thread = find_thread_ptid (cs.general_thread);
4681 if (thread == NULL)
4682 thread = get_first_thread ();
4683 thread_id = thread->id;
4686 cs.general_thread = thread_id;
4687 set_desired_thread ();
4688 gdb_assert (current_thread != NULL);
4690 else if (cs.own_buf[1] == 'c')
4691 cs.cont_thread = thread_id;
4693 write_ok (cs.own_buf);
4695 else
4697 /* Silently ignore it so that gdb can extend the protocol
4698 without compatibility headaches. */
4699 cs.own_buf[0] = '\0';
4701 break;
4702 case 'g':
4703 require_running_or_break (cs.own_buf);
4704 if (cs.current_traceframe >= 0)
4706 struct regcache *regcache
4707 = new_register_cache (current_target_desc ());
4709 if (fetch_traceframe_registers (cs.current_traceframe,
4710 regcache, -1) == 0)
4711 registers_to_string (regcache, cs.own_buf);
4712 else
4713 write_enn (cs.own_buf);
4714 free_register_cache (regcache);
4716 else
4718 struct regcache *regcache;
4720 if (!set_desired_thread ())
4721 write_enn (cs.own_buf);
4722 else
4724 regcache = get_thread_regcache (current_thread, 1);
4725 registers_to_string (regcache, cs.own_buf);
4728 break;
4729 case 'G':
4730 require_running_or_break (cs.own_buf);
4731 if (cs.current_traceframe >= 0)
4732 write_enn (cs.own_buf);
4733 else
4735 struct regcache *regcache;
4737 if (!set_desired_thread ())
4738 write_enn (cs.own_buf);
4739 else
4741 regcache = get_thread_regcache (current_thread, 1);
4742 registers_from_string (regcache, &cs.own_buf[1]);
4743 write_ok (cs.own_buf);
4746 break;
4747 case 'm':
4749 require_running_or_break (cs.own_buf);
4750 decode_m_packet (&cs.own_buf[1], &mem_addr, &len);
4751 int res = gdb_read_memory (mem_addr, mem_buf, len);
4752 if (res < 0)
4753 write_enn (cs.own_buf);
4754 else
4755 bin2hex (mem_buf, cs.own_buf, res);
4757 break;
4758 case 'M':
4759 require_running_or_break (cs.own_buf);
4760 decode_M_packet (&cs.own_buf[1], &mem_addr, &len, &mem_buf);
4761 if (gdb_write_memory (mem_addr, mem_buf, len) == 0)
4762 write_ok (cs.own_buf);
4763 else
4764 write_enn (cs.own_buf);
4765 break;
4766 case 'X':
4767 require_running_or_break (cs.own_buf);
4768 if (decode_X_packet (&cs.own_buf[1], packet_len - 1,
4769 &mem_addr, &len, &mem_buf) < 0
4770 || gdb_write_memory (mem_addr, mem_buf, len) != 0)
4771 write_enn (cs.own_buf);
4772 else
4773 write_ok (cs.own_buf);
4774 break;
4775 case 'C':
4776 require_running_or_break (cs.own_buf);
4777 hex2bin (cs.own_buf + 1, &sig, 1);
4778 if (gdb_signal_to_host_p ((enum gdb_signal) sig))
4779 signal = gdb_signal_to_host ((enum gdb_signal) sig);
4780 else
4781 signal = 0;
4782 myresume (cs.own_buf, 0, signal);
4783 break;
4784 case 'S':
4785 require_running_or_break (cs.own_buf);
4786 hex2bin (cs.own_buf + 1, &sig, 1);
4787 if (gdb_signal_to_host_p ((enum gdb_signal) sig))
4788 signal = gdb_signal_to_host ((enum gdb_signal) sig);
4789 else
4790 signal = 0;
4791 myresume (cs.own_buf, 1, signal);
4792 break;
4793 case 'c':
4794 require_running_or_break (cs.own_buf);
4795 signal = 0;
4796 myresume (cs.own_buf, 0, signal);
4797 break;
4798 case 's':
4799 require_running_or_break (cs.own_buf);
4800 signal = 0;
4801 myresume (cs.own_buf, 1, signal);
4802 break;
4803 case 'Z': /* insert_ ... */
4804 /* Fallthrough. */
4805 case 'z': /* remove_ ... */
4807 char *dataptr;
4808 ULONGEST addr;
4809 int kind;
4810 char type = cs.own_buf[1];
4811 int res;
4812 const int insert = ch == 'Z';
4813 const char *p = &cs.own_buf[3];
4815 p = unpack_varlen_hex (p, &addr);
4816 kind = strtol (p + 1, &dataptr, 16);
4818 if (insert)
4820 struct gdb_breakpoint *bp;
4822 bp = set_gdb_breakpoint (type, addr, kind, &res);
4823 if (bp != NULL)
4825 res = 0;
4827 /* GDB may have sent us a list of *point parameters to
4828 be evaluated on the target's side. Read such list
4829 here. If we already have a list of parameters, GDB
4830 is telling us to drop that list and use this one
4831 instead. */
4832 clear_breakpoint_conditions_and_commands (bp);
4833 const char *options = dataptr;
4834 process_point_options (bp, &options);
4837 else
4838 res = delete_gdb_breakpoint (type, addr, kind);
4840 if (res == 0)
4841 write_ok (cs.own_buf);
4842 else if (res == 1)
4843 /* Unsupported. */
4844 cs.own_buf[0] = '\0';
4845 else
4846 write_enn (cs.own_buf);
4847 break;
4849 case 'k':
4850 response_needed = false;
4851 if (!target_running ())
4852 /* The packet we received doesn't make sense - but we can't
4853 reply to it, either. */
4854 return 0;
4856 fprintf (stderr, "Killing all inferiors\n");
4858 for_each_process (kill_inferior_callback);
4860 /* When using the extended protocol, we wait with no program
4861 running. The traditional protocol will exit instead. */
4862 if (extended_protocol)
4864 cs.last_status.set_exited (GDB_SIGNAL_KILL);
4865 return 0;
4867 else
4868 exit (0);
4870 case 'T':
4872 require_running_or_break (cs.own_buf);
4874 ptid_t thread_id = read_ptid (&cs.own_buf[1], NULL);
4875 if (find_thread_ptid (thread_id) == NULL)
4877 write_enn (cs.own_buf);
4878 break;
4881 if (mythread_alive (thread_id))
4882 write_ok (cs.own_buf);
4883 else
4884 write_enn (cs.own_buf);
4886 break;
4887 case 'R':
4888 response_needed = false;
4890 /* Restarting the inferior is only supported in the extended
4891 protocol. */
4892 if (extended_protocol)
4894 if (target_running ())
4895 for_each_process (kill_inferior_callback);
4897 fprintf (stderr, "GDBserver restarting\n");
4899 /* Wait till we are at 1st instruction in prog. */
4900 if (program_path.get () != NULL)
4902 target_create_inferior (program_path.get (), program_args);
4904 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
4906 /* Stopped at the first instruction of the target
4907 process. */
4908 cs.general_thread = cs.last_ptid;
4910 else
4912 /* Something went wrong. */
4913 cs.general_thread = null_ptid;
4916 else
4918 cs.last_status.set_exited (GDB_SIGNAL_KILL);
4920 return 0;
4922 else
4924 /* It is a request we don't understand. Respond with an
4925 empty packet so that gdb knows that we don't support this
4926 request. */
4927 cs.own_buf[0] = '\0';
4928 break;
4930 case 'v':
4931 /* Extended (long) request. */
4932 handle_v_requests (cs.own_buf, packet_len, &new_packet_len);
4933 break;
4935 default:
4936 /* It is a request we don't understand. Respond with an empty
4937 packet so that gdb knows that we don't support this
4938 request. */
4939 cs.own_buf[0] = '\0';
4940 break;
4943 if (new_packet_len != -1)
4944 putpkt_binary (cs.own_buf, new_packet_len);
4945 else
4946 putpkt (cs.own_buf);
4948 response_needed = false;
4950 if (exit_requested)
4951 return -1;
4953 return 0;
4956 /* Event-loop callback for serial events. */
4958 void
4959 handle_serial_event (int err, gdb_client_data client_data)
4961 threads_debug_printf ("handling possible serial event");
4963 /* Really handle it. */
4964 if (process_serial_event () < 0)
4966 keep_processing_events = false;
4967 return;
4970 /* Be sure to not change the selected thread behind GDB's back.
4971 Important in the non-stop mode asynchronous protocol. */
4972 set_desired_thread ();
4975 /* Push a stop notification on the notification queue. */
4977 static void
4978 push_stop_notification (ptid_t ptid, const target_waitstatus &status)
4980 struct vstop_notif *vstop_notif = new struct vstop_notif;
4982 vstop_notif->status = status;
4983 vstop_notif->ptid = ptid;
4984 /* Push Stop notification. */
4985 notif_push (&notif_stop, vstop_notif);
4988 /* Event-loop callback for target events. */
4990 void
4991 handle_target_event (int err, gdb_client_data client_data)
4993 client_state &cs = get_client_state ();
4994 threads_debug_printf ("handling possible target event");
4996 cs.last_ptid = mywait (minus_one_ptid, &cs.last_status,
4997 TARGET_WNOHANG, 1);
4999 if (cs.last_status.kind () == TARGET_WAITKIND_NO_RESUMED)
5001 if (gdb_connected () && report_no_resumed)
5002 push_stop_notification (null_ptid, cs.last_status);
5004 else if (cs.last_status.kind () != TARGET_WAITKIND_IGNORE)
5006 int pid = cs.last_ptid.pid ();
5007 struct process_info *process = find_process_pid (pid);
5008 int forward_event = !gdb_connected () || process->gdb_detached;
5010 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
5011 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
5013 mark_breakpoints_out (process);
5014 target_mourn_inferior (cs.last_ptid);
5016 else if (cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED)
5018 else
5020 /* We're reporting this thread as stopped. Update its
5021 "want-stopped" state to what the client wants, until it
5022 gets a new resume action. */
5023 current_thread->last_resume_kind = resume_stop;
5024 current_thread->last_status = cs.last_status;
5027 if (forward_event)
5029 if (!target_running ())
5031 /* The last process exited. We're done. */
5032 exit (0);
5035 if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
5036 || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED
5037 || cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED)
5039 else
5041 /* A thread stopped with a signal, but gdb isn't
5042 connected to handle it. Pass it down to the
5043 inferior, as if it wasn't being traced. */
5044 enum gdb_signal signal;
5046 threads_debug_printf ("GDB not connected; forwarding event %d for"
5047 " [%s]",
5048 (int) cs.last_status.kind (),
5049 target_pid_to_str (cs.last_ptid).c_str ());
5051 if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
5052 signal = cs.last_status.sig ();
5053 else
5054 signal = GDB_SIGNAL_0;
5055 target_continue (cs.last_ptid, signal);
5058 else
5060 push_stop_notification (cs.last_ptid, cs.last_status);
5062 if (cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED
5063 && !target_any_resumed ())
5065 target_waitstatus ws;
5066 ws.set_no_resumed ();
5067 push_stop_notification (null_ptid, ws);
5072 /* Be sure to not change the selected thread behind GDB's back.
5073 Important in the non-stop mode asynchronous protocol. */
5074 set_desired_thread ();
5077 /* See gdbsupport/event-loop.h. */
5080 invoke_async_signal_handlers ()
5082 return 0;
5085 /* See gdbsupport/event-loop.h. */
5088 check_async_event_handlers ()
5090 return 0;
5093 /* See gdbsupport/errors.h */
5095 void
5096 flush_streams ()
5098 fflush (stdout);
5099 fflush (stderr);
5102 /* See gdbsupport/gdb_select.h. */
5105 gdb_select (int n, fd_set *readfds, fd_set *writefds,
5106 fd_set *exceptfds, struct timeval *timeout)
5108 return select (n, readfds, writefds, exceptfds, timeout);
5111 #if GDB_SELF_TEST
5112 namespace selftests
5115 void
5116 reset ()
5119 } // namespace selftests
5120 #endif /* GDB_SELF_TEST */